我知道可以使用以下方法更改文件的权限模式:
Runtime.getRuntime().exec( "chmod 777 myfile");
。
此示例将权限位设置为 777
。是否可以使用 Java 以编程方式将权限位设置为 777
?可以对每个文件都这样做吗?
最佳答案
在 Android 中使用 chmod
Java 本身不支持依赖于平台的操作,例如 chmod。但是,Android 通过 android.os.FileUtils 为其中一些操作提供实用程序。 FileUtils 类不是公共(public) 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);
...
关于java - 如何在 Java 中以编程方式获取文件权限模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11408154/