List of usage examples for android.support.v4.provider DocumentFile fromTreeUri
public static DocumentFile fromTreeUri(Context context, Uri uri)
From source file:com.kanedias.vanilla.lyrics.LyricsShowActivity.java
/** * Write lyrics to *.lrc file through SAF framework - the only way to do it in Android > 4.4 when working with SD card *//*ww w . j ava 2 s. c om*/ private void writeThroughSaf(byte[] data, File original, String name) { DocumentFile originalRef; if (mPrefs.contains(PREF_SDCARD_URI)) { // no sorcery can allow you to gain URI to the document representing file you've been provided with // you have to find it again now using Document API // /storage/volume/Music/some.mp3 will become [storage, volume, music, some.mp3] List<String> pathSegments = new ArrayList<>(Arrays.asList(original.getAbsolutePath().split("/"))); Uri allowedSdRoot = Uri.parse(mPrefs.getString(PREF_SDCARD_URI, "")); originalRef = findInDocumentTree(DocumentFile.fromTreeUri(this, allowedSdRoot), pathSegments); } else { // user will click the button again return; } if (originalRef == null || originalRef.getParentFile() == null) { // nothing selected or invalid file? Toast.makeText(this, R.string.saf_nothing_selected, Toast.LENGTH_LONG).show(); return; } DocumentFile lrcFileRef = originalRef.getParentFile().createFile("image/*", name); if (lrcFileRef == null) { // couldn't create file? Toast.makeText(this, R.string.saf_write_error, Toast.LENGTH_LONG).show(); return; } try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(lrcFileRef.getUri(), "rw"); if (pfd == null) { // should not happen Log.e(LOG_TAG, "SAF provided incorrect URI!" + lrcFileRef.getUri()); return; } FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor()); fos.write(data); fos.close(); // rescan original file Toast.makeText(this, R.string.file_written_successfully, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, getString(R.string.saf_write_error) + e.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); Log.e(LOG_TAG, "Failed to write to file descriptor provided by SAF!", e); } }
From source file:com.filemanager.free.filesystem.FileUtil.java
/** * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not * existing, it is created.//from w ww . j a v a 2 s . com * * @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("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; }
From source file:com.xperia64.timidityae.Globals.java
public static boolean renameDocumentFile(Context c, String from, String subTo) { // From is the full path // subTo is the path without the device prefix. // So /storage/sdcard1/folder/file.mid should be folder/file.mid if (theFold == null) return false; from = from.replace("//", "/"); subTo = subTo.replace("//", "/"); DocumentFile df = DocumentFile.fromTreeUri(c, theFold); String split[] = from.split("/"); int i;// w ww.jav a 2 s. c o m for (i = 0; i < split.length; i++) { if (split[i].equals(df.getName())) { i++; break; } } DocumentFile xx = df; StringBuilder upper = new StringBuilder(); while (i < split.length) { xx = xx.findFile(split[i++]); upper.append("../"); if (xx == null) { Log.e("TimidityAE Globals", "Rename file error."); break; } } if (xx != null && upper.length() > 3) { return xx.renameTo(upper.substring(0, upper.length() - 3) + subTo); } return false; }
From source file:com.xperia64.timidityae.Globals.java
public static void tryToDeleteFile(Context c, String filename) { filename = filename.replace("//", "/"); if (new File(filename).exists()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { DocumentFile df = DocumentFile.fromTreeUri(c, theFold); String split[] = filename.split("/"); int i; for (i = 0; i < split.length; i++) { if (split[i].equals(df.getName())) { i++;/*from ww w.j ava2s .c o m*/ break; } } DocumentFile xx = df; while (i < split.length) { xx = xx.findFile(split[i++]); //upper.append("../"); if (xx == null) { Log.e("TimidityAE Globals", "Delete file error."); break; } } // Why on earth is DocumentFile's delete method recursive by default? // Seriously. I wiped my sd card twice because of this. if (xx != null && xx.isFile() && !xx.isDirectory()) { xx.delete(); } } else { new File(filename).delete(); } } }
From source file:com.farmerbb.notepad.activity.MainActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override/*from ww w . j a va 2s.c om*/ 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) reallyExportNotes(); 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); } } }
From source file:com.xperia64.timidityae.Globals.java
public static void tryToCreateFile(Context c, String filename) { filename = filename.replace("//", "/"); if (!(new File(filename).exists())) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && theFold != null) { DocumentFile df = DocumentFile.fromTreeUri(c, theFold); String split[] = filename.split("/"); int i; for (i = 0; i < split.length; i++) { if (split[i].equals(df.getName())) { i++;//from w ww . j a v a 2s . c om break; } } DocumentFile xx = df; while (i < split.length - 1) { xx = xx.findFile(split[i++]); if (xx == null) { Log.e("TimidityAE Globals", "Create file error."); break; } } if (xx != null) { xx.createFile("timidityae/tpl", split[split.length - 1]); } } else { try { new File(filename).createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.anjalimacwan.MainActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override// ww w.j ava 2 s . c o m 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.anjalimacwan.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); } 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()))); saveExportedNote(loadNote(exportFilename.toString()), file.getUri()); } catch (IOException e) { successful = false; } } showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes); } } }
From source file:com.almalence.opencam.SavingService.java
@TargetApi(19) public static DocumentFile getSaveDirNew(boolean forceSaveToInternalMemory) { DocumentFile saveDir = null;//from w w w.j a va 2s.co m boolean usePhoneMem = true; String abcDir = "Camera"; if (sortByData) { Calendar rightNow = Calendar.getInstance(); abcDir = String.format("%tF", rightNow); } int saveToValue = Integer.parseInt(saveToPreference); if (saveToValue == 1 || saveToValue == 2) { boolean canWrite = false; String uri = saveToPath; try { saveDir = DocumentFile.fromTreeUri(ApplicationScreen.instance, Uri.parse(uri)); } catch (Exception e) { saveDir = null; } List<UriPermission> perms = ApplicationScreen.instance.getContentResolver() .getPersistedUriPermissions(); for (UriPermission p : perms) { if (p.getUri().toString().equals(uri.toString()) && p.isWritePermission()) { canWrite = true; break; } } if (saveDir != null && canWrite && saveDir.exists()) { if (sortByData) { DocumentFile dateFolder = saveDir.findFile(abcDir); if (dateFolder == null) { dateFolder = saveDir.createDirectory(abcDir); } saveDir = dateFolder; } usePhoneMem = false; } } if (usePhoneMem || forceSaveToInternalMemory) // phone memory (internal // sd card) { saveDir = DocumentFile .fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)); DocumentFile abcFolder = saveDir.findFile(abcDir); if (abcFolder == null || !abcFolder.exists()) { abcFolder = saveDir.createDirectory(abcDir); } saveDir = abcFolder; } return saveDir; }