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

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

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

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

在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); ... 

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

除了通过Intents之外,Android很难与其他应用程序及其数据进行交互。 意图不适用于权限,因为您依赖于接收Intent的应用程序来执行/提供您想要的内容; 它们可能不是为了告诉任何人他们的文件权限。 有很多方法,但只有当应用程序被设计为在同一个JVM中运行时。 所以每个应用程序只能更改它的文件。 有关文件权限的更多详细信息,请参阅http://docs.oracle.com/javase/1.4.2/docs/guide/security/permissions.html

如前所述, android.os.FileUtils已经改变,Ashraf发布的解决方案不再有效。 以下方法适用于所有Android版本(尽管它确实使用了reflection,如果制造商进行了重大更改,则可能无效)。

 public static void chmod(String path, int mode) throws Exception { Class libcore = Class.forName("libcore.io.Libcore"); Field field = libcore.getDeclaredField("os"); if (!field.isAccessible()) { field.setAccessible(true); } Object os = field.get(field); Method chmod = os.getClass().getMethod("chmod", String.class, int.class); chmod.invoke(os, path, mode); } 

显然,您需要拥有该文件才能进行任何权限更改。

这是一个使用Apache Commons.IO FileUtils的解决方案,以及File对象上的相应方法。

 for (File f : FileUtils.listFilesAndDirs(new File('/some/path'), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { if (!f.setReadable(true, false)) { throw new IOException(String.format("Failed to setReadable for all on %s", f)); } if (!f.setWritable(true, false)) { throw new IOException(String.format("Failed to setWritable for all on %s", f)); } if (!f.setExecutable(true, false)) { throw new IOException(String.format("Failed to setExecutable for all on %s", f)); } } 

这相当于chmod -R 0777 /some/path 。 调整set{Read,Writ,Execut}able调用以实现其他模式。 (如果有人发布适当的代码来执行此操作,我会很高兴地更新此答案。)