我知道可以使用以下代码更改文件的权限模式:
Runtime.getRuntime().exec( "chmod 777 myfile" );
这个例子将权限位设置为777
。是否可以使用Java编程以编程方式将权限位设置为777
? 这可以对每个文件执行吗?
我知道可以使用以下代码更改文件的权限模式:
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);
...
该文章介绍了在Android中使用chmod命令更改文件权限的方法。首先需要确保设备已经root,然后通过Java代码执行shell命令来调用chmod并更改文件权限。Android使与其他应用程序及其数据交互变得困难,除非通过意图。 意图无法用于权限,因为您依赖于接收意图的应用程序来执行/提供您想要的内容; 他们可能没有设计为告诉任何人他们文件的权限。 有绕过它的方法,但仅当应用程序被设计为在同一JVM中运行时才可以。 因此,每个应用程序只能更改自己的文件。 有关文件权限的更多详细信息,请参见http://docs.oracle.com/javase/1.4.2/docs/guide/security/permissions.html。
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);
}
这里有一个使用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
,通常情况下该类被SDK隐藏。但是,如果您不想调用#exec(..)
,则可以使用反射来访问它。 - Jens