如何在Java中以编程方式获取文件权限模式

Sat*_*ish 4 java android file-permissions

我知道可以使用以下方法更改文件的权限模式:

Runtime.getRuntime().exec( "chmod 777 myfile" );.

此示例将权限位设置为777.是否可以777使用Java 以编程方式设置权限位?这可以对每个文件进行吗?

Ash*_*raf 9

在Android中使用chmod

Java没有像chmod这样的平台相关操作的原生支持.但是,Android通过android.os.FileUtils为其中一些操作提供实用程序.FileUtils类不是公共SDK的一部分,因此不受支持.因此,使用此风险需要您自担风险:

public int chmod(File path, int mode) throws Exception {
 Class fileUtils = Class.forName("android.os.FileUtils");
Method setPermissions =
  fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class);
return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1);
}

...
chmod("/foo/bar/baz", 0755);
...
Run Code Online (Sandbox Code Playgroud)

参考:http://www.damonkohler.com/2010/05/using-chmod-in-android.html? showComment= 1341900716400#c4186506545056003185