【问题标题】:How to set rw- r-- r-- permissions programmatically?如何以编程方式设置 rw- r-- r-- 权限?
【发布时间】:2013-01-11 14:47:35
【问题描述】:

我正在开发一个应用程序,可以将应用程序的数据恢复到 /data/data/{packageName}。恢复文件后,我将权限设置为 rw- r-- r--。我是这样设置的:

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(file, 644);

但是当我在文件资源管理器中检查这些文件的权限时,它会显示“--- rwx r-x”。

那么如何设置权限为 rw- r-- r--?

【问题讨论】:

  • 我认为您需要超级用户访问权限才能这样做
  • 是的。我已经获得了 SU 访问权限。字符串 cmd = "cp -r " + sourceFile.getAbsolutePath() + "/* " + destinationFile.getAbsolutePath() + "/"; Runtime.getRuntime().exec(new String[] { "su", cmd }); chmod(destinationFile, 644);
  • @Rajkiran 我也想更改文件的权限,在搜索时我遇到了你的问题。我尝试了相同的代码,但在 android.os 包中找不到 FileUtils 类。你是怎么用的??请回复here
  • 您真正搜索的是什么? android.os 包有一个同名的文件。源代码:grepcode.com/file/repository.grepcode.com/java/ext/…

标签: android file-permissions


【解决方案1】:
Process process = null;
DataOutputStream dataOutputStream = null;

try {
    process = Runtime.getRuntime().exec("su");
    dataOutputStream = new DataOutputStream(process.getOutputStream());
    dataOutputStream.writeBytes("chmod 644 FilePath\n");
    dataOutputStream.writeBytes("exit\n");
    dataOutputStream.flush();
    process.waitFor();
} catch (Exception e) {
    return false;
} finally {
    try {
        if (dataOutputStream != null) {
            dataOutputStream.close();
        }
        process.destroy();
    } catch (Exception e) {
    }
}

【讨论】:

    【解决方案2】:

    值错了,正确的是420(十进制的420就是八进制的644)。或者,您可以添加前导 0 以使其成为 java 八进制文字。 即

    chmod(destinationFile, 0644)
    

    【讨论】:

    • 哦,谢谢。但正如您在我的第二条评论中看到的那样,我正在使用命令在 SU 模式下复制文件。所以我会和@android_test一起去寻找答案。总之,点赞。 :)
    【解决方案3】:

    您应该能够使用以下方法对文件设置这些权限 (rw- r-- r--):

    path.setReadOnly(true); //Sets all permissions for every owner back to read-only
    path.setWritable(true); //Sets the owner's permissions to writeable
    

    其中path 是您的File 对象。

    您不需要使用带反射的 FileUtils 来设置文件的权限。 您可以只使用 File 类上的辅助方法。 使用文件,您还可以调用:setReadable()setWritable()setExecutable()

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多