Java Code Examples for android.support.v4.provider.DocumentFile

The following examples show how to use android.support.v4.provider.DocumentFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: YTPlayer   Source File: OPlaylistFragment.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 101) {
        if (resultCode== Activity.RESULT_OK)
            YTutils.showInterstitialAd(activity);
    }
    if (requestCode == 42) {
        Uri treeUri = data.getData();
        DocumentFile pickedDir = DocumentFile.fromTreeUri(activity, treeUri);
        activity.grantUriPermission(activity.getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        activity.getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("ext_sdcard", treeUri.toString());
        editor.apply();

        Toast.makeText(activity, "Permission granted, try to delete file again!", Toast.LENGTH_LONG).show();
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 2
Source Project: PowerFileExplorer   Source File: HFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Helper method to check file existence in otg
 *
 * @param context
 * @return
 */
public boolean exists(Context context) {
    if (isOtgFile()) {
        DocumentFile fileToCheck = OTGUtil.getDocumentFile(path, context, false);
        return fileToCheck != null;
    } else return (exists());
}
 
Example 3
Source Project: PowerFileExplorer   Source File: Futils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Open file from OTG
 * @param f
 * @param c
 * @param forcechooser
 */
public void openunknown(DocumentFile f, Context c, boolean forcechooser) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        intent.setDataAndType(f.getUri(), type);
        Intent startintent;
        if (forcechooser) startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}
 
Example 4
/**
 * 通过segment片段定位到parent的指定文件夹,如果没有则尝试创建
 */
public static @NonNull DocumentFile getDocumentFileBySegments(@NonNull DocumentFile parent, @Nullable String segment) throws Exception{
    if(segment==null)return parent;
    String[]segments=segment.split("/");
    DocumentFile documentFile=parent;
    for(int i=0;i<segments.length;i++){
        DocumentFile lookup=documentFile.findFile(segments[i]);
        if(lookup==null){
            lookup=documentFile.createDirectory(segments[i]);
        }
        if(lookup==null){
            throw new Exception("Can not create folder "+segments[i]);
        }
        documentFile=lookup;
    }
    return documentFile;
}
 
Example 5
Source Project: Rey-MusicPlayer   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
        if (fileOrDirectory.listFiles() != null)
            for (File child : fileOrDirectory.listFiles()) {
                return deleteRecursive(child);
            }

    if (MusicUtils.isKitkat() || !MusicUtils.isFromSdCard(fileOrDirectory.getAbsolutePath())) {
        if (fileOrDirectory.delete()) {
            return MusicUtils.deleteViaContentProvider(fileOrDirectory.getAbsolutePath());
        }

    } else {
        DocumentFile documentFile = getDocumentFile(fileOrDirectory);
        if (documentFile.delete()) {
            return MusicUtils.deleteViaContentProvider(fileOrDirectory.getAbsolutePath());
        }
    }
    return false;
}
 
Example 6
Source Project: Rey-MusicPlayer   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void rename(File file, String fileName) {

        if (MusicUtils.isFromSdCard(file.getAbsolutePath())) {
            DocumentFile documentFile = getDocumentFile(file);
            documentFile.renameTo(fileName);
        } else {
            File parentFile = file.getParentFile();

            if (!parentFile.exists())
                parentFile.mkdir();

            File file1 = new File(parentFile, fileName);
            file.renameTo(file1);
            file.delete();
        }

    }
 
Example 7
Source Project: Rey-MusicPlayer   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean deleteFile(File file) {
    if (file == null) {
        throw new NullPointerException("File can't be null");
    }
    if (MusicUtils.isFromSdCard(file.getAbsolutePath())) {
        DocumentFile documentFile = getDocumentFile(file);
        if (documentFile.isDirectory()) {
            deleteDirectory(documentFile);
        } else {
            Logger.log("Deleted File Name  " + file.getName());
            return documentFile.delete();
        }
    } else {
        return file.delete();
    }
    return false;
}
 
Example 8
Source Project: Camera-Roll-Android-App   Source File: Copy.java    License: Apache License 2.0 6 votes vote down vote up
static boolean copyFileOntoRemovableStorage(Context context, Uri treeUri,
                                            String path, String destination) throws IOException {
    String mimeType = MediaType.getMimeType(path);
    DocumentFile file = DocumentFile.fromFile(new File(destination));
    if (file.exists()) {
        int index = destination.lastIndexOf(".");
        destination = destination.substring(0, index) + " Copy"
                + destination.substring(index, destination.length());
    }
    DocumentFile destinationFile = StorageUtil.createDocumentFile(context, treeUri, destination, mimeType);

    if (destinationFile != null) {
        ContentResolver resolver = context.getContentResolver();
        OutputStream outputStream = resolver.openOutputStream(destinationFile.getUri());
        InputStream inputStream = new FileInputStream(path);
        return writeStream(inputStream, outputStream);
    }
    return false;
}
 
Example 9
Source Project: Camera-Roll-Android-App   Source File: FileOperation.java    License: Apache License 2.0 6 votes vote down vote up
public Uri getTreeUri(Intent workIntent, String path) {
    Log.d("FileOperation", "getTreeUri");
    Uri treeUri;
    String treeUriExtra = workIntent.getStringExtra(FileOperation.REMOVABLE_STORAGE_TREE_URI);
    if (treeUriExtra != null) {
        treeUri = Uri.parse(treeUriExtra);
    } else {
        Settings s = Settings.getInstance(getApplicationContext());
        treeUri = s.getRemovableStorageTreeUri();
    }

    if (path != null) {
        //check if path is child of the treeUri
        DocumentFile file = StorageUtil.parseDocumentFile(getApplicationContext(), treeUri, new File(path));
        if (file != null) {
            return treeUri;
        } else {
            requestPermissionForRemovableStorageBroadcast(workIntent);
        }
    } else {
        return treeUri;
    }
    return null;
}
 
Example 10
Source Project: Camera-Roll-Android-App   Source File: Rename.java    License: Apache License 2.0 6 votes vote down vote up
private boolean renameFileRemovableStorage(Context context, Uri treeUri, String path, String newFileName) {
    //keep old paths to remove them from MediaStore afterwards
    ArrayList<String> oldPaths = FileOperation.Util.getAllChildPaths(new ArrayList<String>(), path);

    newFilePath = getNewFilePath(path, newFileName);
    boolean success = false;
    DocumentFile file = StorageUtil.parseDocumentFile(context, treeUri, new File(path));
    if (file != null) {
        success = file.renameTo(new File(newFilePath).getName());
    }

    //re-scan all paths
    ArrayList<String> newPaths = FileOperation.Util.getAllChildPaths(new ArrayList<String>(), newFilePath);
    addPathsToScan(oldPaths);
    addPathsToScan(newPaths);
    return success;
}
 
Example 11
Source Project: FileManager   Source File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean renameTarget(String filePath, String newName) {
    File src = new File(filePath);

    String temp = filePath.substring(0, filePath.lastIndexOf("/"));
    File dest = new File(temp + "/" + newName);

    if (src.renameTo(dest)) {
        return true;
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(src);

            if (document.renameTo(dest.getAbsolutePath())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 12
Source Project: FileManager   Source File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean createDir(File folder) {
    if (folder.exists())
        return false;

    if (folder.mkdir())
        return true;
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(folder.getParentFile());
            if (document.exists())
                return true;
        }

        if (Settings.rootAccess()) {
            return RootCommands.createRootdir(folder);
        }
    }

    return false;
}
 
Example 13
public void open(final TGBrowserCallBack<Object> cb){
	try {
		new TGSafBrowserUriRequest(this.context, new TGSafBrowserUriHandler() {
			public void onUriAccessGranted(Uri uri) {
				if( uri != null ) {
					TGSafBrowser.this.root = DocumentFile.fromTreeUri(getActivity(), uri);
					TGSafBrowser.this.element = null;

					cb.onSuccess(TGSafBrowser.this.element);
				} else {
					cb.handleError(new TGBrowserException(getActivity().getString(R.string.browser_settings_saf_error_uri_access)));
				}
			}
		}, this.data.getUri()).process();
	} catch (RuntimeException e) {
		cb.handleError(e);
	}
}
 
Example 14
public void listElements(TGBrowserCallBack<List<TGBrowserElement>> cb) {
	try {
		List<TGBrowserElement> elements = new ArrayList<TGBrowserElement>();
		if( this.element != null ) {
			DocumentFile file = this.element.getFile();
			if( file.exists() && file.isDirectory() ) {
				DocumentFile[] children = file.listFiles();
				if( children != null ) {
					for(DocumentFile child : children){
						elements.add(new TGSafBrowserElement(child, this.element));
					}
				}
			}
			if( !elements.isEmpty() ){
				Collections.sort(elements, new TGBrowserElementComparator());
			}
		}

		cb.onSuccess(elements);
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example 15
Source Project: ToGoZip   Source File: SettingsImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * calculates the dafault-path value for 2go.zip
 */
public static String getDefaultZipDirPath(Context context) {
    File rootDir = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        // before api-14/android-4.4/KITKAT
        // write support on sdcard, if mounted
        Boolean isSDPresent = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        rootDir = ((isSDPresent)) ? Environment.getExternalStorageDirectory() : Environment.getRootDirectory();
    } else if (Global.USE_DOCUMENT_PROVIDER && (zipDocDirUri != null)) {

        // DocumentFile docDir = DocumentFile.fromTreeUri(context, Uri.parse(zipDocDirUri));
        DocumentFile docDir = DocumentFile.fromFile(new File(zipDocDirUri));
        if ((docDir != null) && docDir.canWrite()) {
            return rootDir.getAbsolutePath();
        }
    }

    if (rootDir == null) {
        // since android 4.4 Environment.getDataDirectory() and .getDownloadCacheDirectory ()
        // is protected by android-os :-(
        rootDir = getRootDir44();
    }

    final String zipfile = rootDir.getAbsolutePath() + "/copy";
    return zipfile;
}
 
Example 16
Source Project: ToGoZip   Source File: SettingsImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * return true if outputdirectory of zipfile is writable
 */
public static boolean canWrite(Context context, String dir) {
    if ((dir == null) || (dir.trim().length() == 0)) {
        return false; // empty is no valid path
    }

    if (Global.USE_DOCUMENT_PROVIDER) {
        DocumentFile docDir = getDocFile(context, dir);
        return ((docDir != null) && (docDir.exists()) && docDir.canWrite());
    }

    File fileDir = new File(dir);
    if ((fileDir == null) || (!fileDir.exists() && !fileDir.mkdirs())) {
        return false; // parentdir does not exist and cannot be created
    }

    return true; // (parentDir.canWrite());
}
 
Example 17
Source Project: ToGoZip   Source File: SettingsImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static DocumentFile getDocFile(Context context, @NonNull String dir ) {
    DocumentFile docDir = null;

    if (dir.indexOf(":") >= 0) {
        Uri uri = Uri.parse(dir);

        if ("file".equals(uri.getScheme())) {
            File fileDir = new File(uri.getPath());
            docDir = DocumentFile.fromFile(fileDir);
        } else {
            docDir = DocumentFile.fromTreeUri(context, uri);
        }
    } else {
        docDir = DocumentFile.fromFile(new File(dir));
    }
    return docDir;

}
 
Example 18
/**
 *  {@inheritDoc}
 */
@Override
public OutputStream createOutputStream(ZipInstance zipInstance) throws FileNotFoundException {
    // find existing
    DocumentFile zipFile = getDocumentFile(zipInstance);

    // if not found create it.
    if (zipFile == null) {
        final String mimetype = (zipInstance == ZipInstance.logfile) ? MIMETYPE_TEXT : MIMETYPE_ZIP;
        zipFile = directory.createFile(mimetype, getZipFileNameWithoutPath(zipInstance));
    }

    if (zipFile != null) return context.getContentResolver().openOutputStream(zipFile.getUri(), "w");

    return null;
}
 
Example 19
/**
 * Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting
 * from the given directory, looking at files first before recursing into
 * directories.  This is "depth last" since the index file is much more
 * likely to be shallow than deep, and there can be a lot of files to
 * search through starting at 4 or more levels deep, like the fdroid
 * icons dirs and the per-app "external storage" dirs.
 */
private void searchDirectory(DocumentFile documentFileDir) {
    DocumentFile[] documentFiles = documentFileDir.listFiles();
    if (documentFiles == null) {
        return;
    }
    boolean foundIndex = false;
    ArrayList<DocumentFile> dirs = new ArrayList<>();
    for (DocumentFile documentFile : documentFiles) {
        if (documentFile.isDirectory()) {
            dirs.add(documentFile);
        } else if (!foundIndex) {
            if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {
                registerRepo(documentFile);
                foundIndex = true;
            }
        }
    }
    for (DocumentFile dir : dirs) {
        searchDirectory(dir);
    }
}
 
Example 20
Source Project: SimpleExplorer   Source File: SimpleUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static boolean renameTarget(String filePath, String newName) {
    File src = new File(filePath);

    String temp = filePath.substring(0, filePath.lastIndexOf("/"));
    File dest = new File(temp + "/" + newName);

    if (src.renameTo(dest)) {
        return true;
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(src);

            if (document.renameTo(dest.getAbsolutePath())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 21
Source Project: SimpleExplorer   Source File: SimpleUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static boolean createDir(File folder) {
    if (folder.exists())
        return false;

    if (folder.mkdir())
        return true;
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(folder.getParentFile());
            if (document.exists())
                return true;
        }

        if (Settings.rootAccess()) {
            return RootCommands.createRootdir(folder);
        }
    }

    return false;
}
 
Example 22
Source Project: PowerFileExplorer   Source File: RootHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static BaseFile generateBaseFile(DocumentFile file, boolean showHidden) {
    long size = 0;
    if (!file.isDirectory())
        size = file.length();
    BaseFile baseFile = new BaseFile(file.getName(), parseDocumentFilePermission(file),
            file.lastModified(), size, file.isDirectory());
    baseFile.setName(file.getName());
    baseFile.setMode(OpenMode.OTG);

    return baseFile;
}
 
Example 23
Source Project: PowerFileExplorer   Source File: RootHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String parseDocumentFilePermission(DocumentFile file) {
    String per = "";
    if (file.canRead()) {
        per = per + "r";
    }
    if (file.canWrite()) {
        per = per + "w";
    }
    if (file.canWrite()) {
        per = per + "x";
    }
    return per;
}
 
Example 24
Source Project: PowerFileExplorer   Source File: FileUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
  * Delete a file. May be even on external SD card.
  *
  * @param file the file to be deleted.
  * @return True if successfully deleted.
  */
 static boolean deleteFile(@NonNull final File file, Context context) {
     // First try the normal deletion.
     if (file == null || !file.exists()) 
return true;
     if (file.delete() || deleteFilesInFolder(file, context))
         return true;

     // Try with Storage Access Framework.
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
         final DocumentFile document = getDocumentFile(file, false, context);
if (document != null) {
	return document.delete();
}
     }

     // Try the Kitkat workaround.
     if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
         final ContentResolver resolver = context.getContentResolver();

         try {
             final Uri uri = MediaStoreHack.getUriFromFile(file.getAbsolutePath(), context);
             resolver.delete(uri, null, null);
             return !file.exists();
         } catch (Exception e) {
             Log.e("AmazeFileUtils", "Error when deleting file " + file.getAbsolutePath(), e);
             return false;
         }
     }

     return !file.exists();
 }
 
Example 25
Source Project: PowerFileExplorer   Source File: FileUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @deprecated use {@link #mkdirs(Context, HFile)}
 * @param file  The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(final File file, Context context) {
    if(file==null)
        return false;
    if (file.exists()) {
        // nothing to create.
        return file.isDirectory();
    }

    // Try the normal way
    if (file.mkdirs()) {
        return true;
    }

    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
        DocumentFile document = getDocumentFile(file, true, context);
        // getDocumentFile implicitly creates the directory.
        return document.exists();
    }

    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        try {
            return MediaStoreHack.mkdir(context, file);
        } catch (IOException e) {
            return false;
        }
    }

    return false;
}
 
Example 26
Source Project: PowerFileExplorer   Source File: OTGUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Traverse to a specified path in OTG
 *
 * @param path
 * @param context
 * @param createRecursive flag used to determine whether to create new file while traversing to path,
 *                        in case path is not present. Notably useful in opening an output stream.
 * @return
 */
public static DocumentFile getDocumentFile(String path, Context context, boolean createRecursive) {
    SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
    String rootUriString = manager.getString(ExplorerActivity.KEY_PREF_OTG, null);

    // start with root of SD card and then parse through document tree.
    DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));

    String[] parts = path.split("/");
    for (int i = 0; i < parts.length; i++) {

        if (path.equals("otg:/")) break;
        if (parts[i].equals("otg:") || parts[i].equals("")) continue;
        Log.d(context.getClass().getSimpleName(), "Currently at: " + parts[i]);
        // iterating through the required path to find the end point

        DocumentFile nextDocument = rootUri.findFile(parts[i]);
        if (createRecursive) {
            if (nextDocument == null || !nextDocument.exists()) {
                nextDocument = rootUri.createFile(parts[i].substring(parts[i].lastIndexOf(".")), parts[i]);
                Log.d(context.getClass().getSimpleName(), "NOT FOUND! File created: " + parts[i]);
            }
        }
        rootUri = nextDocument;
    }
    return rootUri;
}
 
Example 27
public static boolean deleteFile(@NonNull final File file, final Context c) {
	// First try the normal deletion.
	if (file.delete()) {
		return true;
	}

	// Try with Storage Access Framework.
	if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
		DocumentFile document = getDocumentFile(file, false, false, c);
		return document != null && document.delete();
	}

	// Try the Kitkat workaround.
	if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
		ContentResolver resolver = c.getContentResolver();

		try {
			Uri uri = getUriFromFile(file.getAbsolutePath(), c);
			if (uri != null) {
				resolver.delete(uri, null, null);
			}
			return !file.exists();
		}
		catch (Exception e) {
			Log.e("Uri", "Error when deleting file " + file.getAbsolutePath(), e);
			return false;
		}
	}

	return !file.exists();
}
 
Example 28
/**
 * Delete a folder.
 *
 * @param file The folder name.
 * @return true if successful.
 */
public static boolean rmdir(@NonNull final File file, final Context c) {
	if (!file.exists()) {
		return true;
	}
	if (!file.isDirectory()) {
		return false;
	}
	String[] fileList = file.list();
	if (fileList != null && fileList.length > 0) {
		// Delete only empty folder.
		return false;
	}

	// 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, true, c);
		return document != null && document.delete();
	}

	// Try the Kitkat workaround.
	if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
		ContentResolver resolver = c.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();
}
 
Example 29
/**
 * 测试是否有写入外置存储的权限
 */
public static boolean canWrite2ExternalStorage(@NonNull Context context){
    SharedPreferences settings= SPUtil.getGlobalSharedPreferences(context);
    String uri_value=settings.getString(Constants.PREFERENCE_SAVE_PATH_URI,"");
    if("".equals(uri_value))return false;
    try{
        return DocumentFile.fromTreeUri(context,Uri.parse(uri_value)).canWrite();
    }catch (Exception e){e.printStackTrace();}
    return false;
}
 
Example 30
/**
 * 获取一个documentFile用于展示的路径
 */
public static @NonNull String getDisplayPathForDocumentFile(@NonNull Context context,@NonNull DocumentFile documentFile){
    String uriPath= documentFile.getUri().getPath();
    if(uriPath==null)return "";
    int index=uriPath.lastIndexOf(":")+1;
    if(index<=uriPath.length())return context.getResources().getString(R.string.external_storage)+"/"+uriPath.substring(index);
    return "";
}