Search in sources :

Example 21 with DocumentFile

use of android.support.v4.provider.DocumentFile in project vlc-android by GeoffreyMetais.

the class FileUtils method findFile.

public static DocumentFile findFile(Uri uri) {
    final String storage = getMediaStorage(uri);
    final String treePref = PreferenceManager.getDefaultSharedPreferences(VLCApplication.getAppContext()).getString("tree_uri_" + storage, null);
    if (treePref == null)
        return null;
    final Uri treeUri = Uri.parse(treePref);
    DocumentFile documentFile = DocumentFile.fromTreeUri(VLCApplication.getAppContext(), treeUri);
    String[] parts = (uri.getPath()).split("/");
    for (int i = 3; i < parts.length; i++) {
        if (documentFile != null)
            documentFile = documentFile.findFile(parts[i]);
        else
            return null;
    }
    if (documentFile != null)
        Log.d(TAG, "findFile: write " + documentFile.canWrite());
    return documentFile;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Uri(android.net.Uri) SuppressLint(android.annotation.SuppressLint)

Example 22 with DocumentFile

use of android.support.v4.provider.DocumentFile in project Notepad by farmerbb.

the class MainActivity method onActivityResult.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == RESULT_OK && resultData != null) {
        successful = true;
        if (requestCode == IMPORT) {
            Uri uri = resultData.getData();
            ClipData clipData = resultData.getClipData();
            if (uri != null)
                successful = importNote(uri);
            else if (clipData != null)
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    successful = importNote(clipData.getItemAt(i).getUri());
                }
            // Show toast notification
            showToast(successful ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully) : R.string.error_importing_notes);
            // Send broadcast to NoteListFragment to refresh list of notes
            Intent listNotesIntent = new Intent();
            listNotesIntent.setAction("com.farmerbb.notepad.LIST_NOTES");
            LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent);
        } else if (requestCode == EXPORT) {
            try {
                saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData());
            } catch (IOException e) {
                successful = false;
            }
            fileBeingExported++;
            if (fileBeingExported < filesToExport.length)
                reallyExportNote();
            else
                showToast(successful ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to) : R.string.error_exporting_notes);
            File fileToDelete = new File(getFilesDir() + File.separator + "exported_note");
            fileToDelete.delete();
        } else if (requestCode == EXPORT_TREE) {
            DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData());
            for (Object exportFilename : filesToExport) {
                try {
                    DocumentFile file = tree.createFile("text/plain", generateFilename(loadNoteTitle(exportFilename.toString())));
                    if (file != null)
                        saveExportedNote(loadNote(exportFilename.toString()), file.getUri());
                    else
                        successful = false;
                } catch (IOException e) {
                    successful = false;
                }
            }
            showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes);
        }
    }
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Intent(android.content.Intent) IOException(java.io.IOException) Uri(android.net.Uri) ClipData(android.content.ClipData) File(java.io.File) DocumentFile(android.support.v4.provider.DocumentFile) SuppressLint(android.annotation.SuppressLint) TargetApi(android.annotation.TargetApi)

Example 23 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class ContentHelper method deleteFile.

/**
 * Delete a file. May be even on external SD card.
 *
 * @param file the file to be deleted.
 * @return True if successfully deleted.
 */
public static boolean deleteFile(Context context, @NonNull final File file) {
    // W/DocumentFile: Failed query: java.lang.IllegalArgumentException: Failed to determine if A613-F0E1:.android_secure is child of A613-F0E1:: java.io.FileNotFoundException: Missing file for A613-F0E1:.android_secure at /storage/sdcard1/.android_secure
    // First try the normal deletion.
    boolean success = file.delete();
    // Try with Storage Access Framework.
    if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, file, false, false);
        success = document != null && document.delete();
    }
    // Try the Kitkat workaround.
    if (!success && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        try {
            // MediaStoreUtil.getUriFromFile(file.getAbsolutePath());
            Uri uri = null;
            if (uri != null) {
                resolver.delete(uri, null, null);
            }
            success = !file.exists();
        } catch (Exception e) {
            Log.e(TAG, "Error when deleting file " + file.getAbsolutePath(), e);
            return false;
        }
    }
    if (success)
        scanFile(context, new String[] { file.getPath() });
    return success;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Uri(android.net.Uri) IOException(java.io.IOException) ContentResolver(android.content.ContentResolver)

Example 24 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class ContentHelper method mkdir.

/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @param dir The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(Context context, @NonNull final File dir) {
    boolean success = dir.exists();
    // Try the normal way
    if (!success)
        success = dir.mkdir();
    // Try with Storage Access Framework.
    if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, dir, true, true);
        // getDocumentFile implicitly creates the directory.
        success = document != null && document.exists();
    }
    // let MediaStore know that a dir was created
    if (success)
        scanFile(context, new String[] { dir.getPath() });
    return success;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile)

Example 25 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class ContentHelper method copyFile.

public static boolean copyFile(Context context, @NonNull final File source, @NonNull final File targetDir) {
    InputStream inStream = null;
    OutputStream outStream = null;
    boolean success = false;
    File target = getTargetFile(source, targetDir);
    try {
        inStream = new FileInputStream(source);
        // First try the normal way
        if (isWritable(target)) {
            // standard way
            FileChannel inChannel = new FileInputStream(source).getChannel();
            FileChannel outChannel = new FileOutputStream(target).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            success = true;
            try {
                inChannel.close();
            } catch (Exception ignored) {
            }
            try {
                outChannel.close();
            } catch (Exception ignored) {
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // outStream = context.getContentResolver().openOutputStream(Uri.fromFile(target));
                if (isFileOnSdCard(context, source)) {
                    DocumentFile sourceDocument = getDocumentFile(context, source, false, false);
                    if (sourceDocument != null) {
                        inStream = context.getContentResolver().openInputStream(sourceDocument.getUri());
                    }
                }
                // Storage Access Framework
                DocumentFile targetDocument = getDocumentFile(context, target, false, false);
                if (targetDocument != null) {
                    outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
                }
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                // TODO: 13/08/16 test this
                // Workaround for Kitkat ext SD card
                Uri uri = getUriFromFile(context, target.getAbsolutePath());
                if (uri != null) {
                    outStream = context.getContentResolver().openOutputStream(uri);
                }
            }
            if (outStream != null) {
                // Both for SAF and for Kitkat, write to output stream.
                // MAGIC_NUMBER
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
                success = true;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e);
        return false;
    } finally {
        try {
            inStream.close();
        } catch (Exception ignored) {
        }
        try {
            outStream.close();
        } catch (Exception ignored) {
        }
    }
    if (success)
        scanFile(context, new String[] { target.getPath() });
    return success;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileChannel(java.nio.channels.FileChannel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Uri(android.net.Uri) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) DocumentFile(android.support.v4.provider.DocumentFile)

Aggregations

DocumentFile (android.support.v4.provider.DocumentFile)65 File (java.io.File)36 IOException (java.io.IOException)22 Uri (android.net.Uri)21 ContentResolver (android.content.ContentResolver)12 SmbFile (jcifs.smb.SmbFile)11 MalformedURLException (java.net.MalformedURLException)10 SmbException (jcifs.smb.SmbException)10 FileOutputStream (java.io.FileOutputStream)9 ShellNotRunningException (com.amaze.filemanager.exceptions.ShellNotRunningException)8 OutputStream (java.io.OutputStream)8 InputStream (java.io.InputStream)7 SuppressLint (android.annotation.SuppressLint)6 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)6 FileInputStream (java.io.FileInputStream)6 SFtpClientTemplate (com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate)4 BufferedOutputStream (java.io.BufferedOutputStream)4 FileNotFoundException (java.io.FileNotFoundException)4 FileChannel (java.nio.channels.FileChannel)4 SFTPClient (net.schmizz.sshj.sftp.SFTPClient)4