Search in sources :

Example 46 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method mkdirs.

public static boolean mkdirs(Context context, HybridFile file) {
    boolean isSuccessful = true;
    switch(file.mode) {
        case SMB:
            try {
                SmbFile smbFile = new SmbFile(file.getPath());
                smbFile.mkdirs();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                isSuccessful = false;
            } catch (SmbException e) {
                e.printStackTrace();
                isSuccessful = false;
            }
            break;
        case OTG:
            DocumentFile documentFile = OTGUtil.getDocumentFile(file.getPath(), context, true);
            isSuccessful = documentFile != null;
            break;
        case FILE:
            isSuccessful = mkdir(new File(file.getPath()), context);
            break;
        default:
            isSuccessful = true;
            break;
    }
    return isSuccessful;
}
Also used : SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) DocumentFile(android.support.v4.provider.DocumentFile) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile) SmbFile(jcifs.smb.SmbFile)

Example 47 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method renameFolder.

/**
 * Rename a folder. In case of extSdCard in Kitkat, the old folder stays in place, but files are moved.
 *
 * @param source The source folder.
 * @param target The target folder.
 * @return true if the renaming was successful.
 */
static boolean renameFolder(@NonNull final File source, @NonNull final File target, Context context) throws ShellNotRunningException {
    // First try the normal rename.
    if (rename(source, target.getName(), false)) {
        return true;
    }
    if (target.exists()) {
        return false;
    }
    // Try the Storage Access Framework if it is just a rename within the same parent folder.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && source.getParent().equals(target.getParent()) && FileUtil.isOnExtSdCard(source, context)) {
        DocumentFile document = getDocumentFile(source, true, context);
        if (document.renameTo(target.getName())) {
            return true;
        }
    }
    // Try the manual way, moving files individually.
    if (!mkdir(target, context)) {
        return false;
    }
    File[] sourceFiles = source.listFiles();
    if (sourceFiles == null) {
        return true;
    }
    for (File sourceFile : sourceFiles) {
        String fileName = sourceFile.getName();
        File targetFile = new File(target, fileName);
        if (!copyFile(sourceFile, targetFile, context)) {
            // stop on first error
            return false;
        }
    }
    // Only after successfully copying all files, delete files on source folder.
    for (File sourceFile : sourceFiles) {
        if (!deleteFile(sourceFile, context)) {
            // stop on first error
            return false;
        }
    }
    return true;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 48 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method getDocumentFile.

/**
 * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not
 * existing, it is created.
 *
 * @param file        The file.
 * @param isDirectory flag indicating if the file should be a directory.
 * @return The DocumentFile
 */
public static DocumentFile getDocumentFile(final File file, final boolean isDirectory, Context context) {
    String baseFolder = getExtSdCardFolder(file, context);
    boolean originalDirectory = false;
    if (baseFolder == null) {
        return null;
    }
    String relativePath = null;
    try {
        String fullPath = file.getCanonicalPath();
        if (!baseFolder.equals(fullPath))
            relativePath = fullPath.substring(baseFolder.length() + 1);
        else
            originalDirectory = true;
    } catch (IOException e) {
        return null;
    } catch (Exception f) {
        originalDirectory = true;
    // continue
    }
    String as = PreferenceManager.getDefaultSharedPreferences(context).getString(PreferencesConstants.PREFERENCE_URI, null);
    Uri treeUri = null;
    if (as != null)
        treeUri = Uri.parse(as);
    if (treeUri == null) {
        return null;
    }
    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
    if (originalDirectory)
        return document;
    String[] parts = relativePath.split("\\/");
    for (int i = 0; i < parts.length; i++) {
        DocumentFile nextDocument = document.findFile(parts[i]);
        if (nextDocument == null) {
            if ((i < parts.length - 1) || isDirectory) {
                nextDocument = document.createDirectory(parts[i]);
            } else {
                nextDocument = document.createFile("image", parts[i]);
            }
        }
        document = nextDocument;
    }
    return document;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) IOException(java.io.IOException) Uri(android.net.Uri) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 49 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method copyFile.

/**
 * Determine the camera folder. There seems to be no Android API to work for real devices, so this is a best guess.
 *
 * @return the default camera folder.
 */
// TODO the function?
/**
 * Copy a file. The target file may even be on external SD card for Kitkat.
 *
 * @param source The source file
 * @param target The target file
 * @return true if the copying was successful.
 */
@SuppressWarnings("null")
private static boolean copyFile(final File source, final File target, Context context) {
    FileInputStream inStream = null;
    OutputStream outStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {
        inStream = new FileInputStream(source);
        // First try the normal way
        if (isWritable(target)) {
            // standard way
            outStream = new FileOutputStream(target);
            inChannel = inStream.getChannel();
            outChannel = ((FileOutputStream) outStream).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Storage Access Framework
                DocumentFile targetDocument = getDocumentFile(target, false, context);
                outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                // Workaround for Kitkat ext SD card
                Uri uri = MediaStoreHack.getUriFromFile(target.getAbsolutePath(), context);
                outStream = context.getContentResolver().openOutputStream(uri);
            } else {
                return false;
            }
            if (outStream != null) {
                // Both for SAF and for Kitkat, write to output stream.
                // MAGIC_NUMBER
                byte[] buffer = new byte[16384];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOG, "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e);
        return false;
    } finally {
        try {
            inStream.close();
        } catch (Exception e) {
        // ignore exception
        }
        try {
            outStream.close();
        } catch (Exception e) {
        // ignore exception
        }
        try {
            inChannel.close();
        } catch (Exception e) {
        // ignore exception
        }
        try {
            outChannel.close();
        } catch (Exception e) {
        // ignore exception
        }
    }
    return true;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) FileChannel(java.nio.channels.FileChannel) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) Uri(android.net.Uri) FileInputStream(java.io.FileInputStream) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 50 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method rmdir.

/**
 * Delete a folder.
 *
 * @param file The folder name.
 * @return true if successful.
 */
private static boolean rmdir(@NonNull final File file, Context context) {
    if (!file.exists())
        return true;
    File[] files = file.listFiles();
    if (files != null && files.length > 0) {
        for (File child : files) {
            rmdir(child, context);
        }
    }
    // Try the normal way
    if (file.delete()) {
        return true;
    }
    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(file, true, context);
        if (document != null && document.delete()) {
            return true;
        }
    }
    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // Delete the created entry, such that content provider will delete the file.
        resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", new String[] { file.getAbsolutePath() });
    }
    return !file.exists();
}
Also used : ContentValues(android.content.ContentValues) DocumentFile(android.support.v4.provider.DocumentFile) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile) ContentResolver(android.content.ContentResolver)

Aggregations

DocumentFile (android.support.v4.provider.DocumentFile)56 File (java.io.File)30 Uri (android.net.Uri)21 IOException (java.io.IOException)17 ContentResolver (android.content.ContentResolver)10 FileOutputStream (java.io.FileOutputStream)8 SuppressLint (android.annotation.SuppressLint)6 InputStream (java.io.InputStream)6 FileInputStream (java.io.FileInputStream)5 OutputStream (java.io.OutputStream)5 MalformedURLException (java.net.MalformedURLException)4 FileChannel (java.nio.channels.FileChannel)4 SmbException (jcifs.smb.SmbException)4 SmbFile (jcifs.smb.SmbFile)4 ContentValues (android.content.ContentValues)3 SharedPreferences (android.content.SharedPreferences)3 ParcelFileDescriptor (android.os.ParcelFileDescriptor)3 ShellNotRunningException (com.amaze.filemanager.exceptions.ShellNotRunningException)3 BufferedOutputStream (java.io.BufferedOutputStream)3 FileNotFoundException (java.io.FileNotFoundException)3