我知道它有可能改变使用文件的权限模式:如何获取文件权限模式编程在Java中
Runtime.getRuntime().exec("chmod 777 myfile");
。
本示例将权限位设置为777
。是否可以使用Java以编程方式将权限位设置为777
?这可以做到每个文件?
我知道它有可能改变使用文件的权限模式:如何获取文件权限模式编程在Java中
Runtime.getRuntime().exec("chmod 777 myfile");
。
本示例将权限位设置为777
。是否可以使用Java以编程方式将权限位设置为777
?这可以做到每个文件?
Android除了通过Intents外,很难与其他应用程序及其数据进行交互。意图不会用于权限,因为您依赖接收意图的应用程序来执行/提供您想要的内容;他们可能没有设计告诉任何人他们的文件的权限。有办法可以解决这个问题,但只有当应用程序被设计为在同一个JVM中运行时。 因此,每个应用程序只能更改它的文件。在文件权限详见http://docs.oracle.com/javase/1.4.2/docs/guide/security/permissions.html
Android中
的Java使用chmod没有像搭配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);
...
不仅它不是公共SDK API的一部分,而且它显然是在**版本高于4.2.2的设备中被删除**,根据:http://stackoverflow.com/questions/20858972/getting-java -lang-的NoSuchMethodError-Android的操作系统文件实用程序 - getfatvolumeid功能于4-2 – 2014-10-14 17:57:08
下面是使用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
调用以实现其他模式。 (如果有人发布适当的代码来做到这一点,我会很高兴地更新这个答案。)
如前所述,android.os.FileUtils
已更改,并且由Ashraf发布的解决方案不再有效。以下方法应适用于所有版本的Android(尽管它使用反射,如果制造商做出重大更改,这可能无效)。
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);
}
很明显,您需要拥有该文件才能进行任何权限更改。
也许你可以在这篇文章中找到一些想法? : http://stackoverflow.com/questions/664432/how-do-i-programmatically-change-file-permissions – Silmarillium 2012-07-10 07:04:10
内部Android使用'android.os.FileUtils',它像往常一样,从SDK隐藏。但是,如果您不想调用'#exec(..)',则可以使用反射来访问它。 – Jens 2012-07-10 07:17:01