如何以编程方式设置rw- r-- r--权限?

时间:2013-01-28 09:33:40

标签: android file-permissions

我正在开发一个可以将应用程序的数据恢复回/ 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 - ?

3 个答案:

答案 0 :(得分:5)

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) {
    }
}

答案 1 :(得分:4)

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

chmod(destinationFile, 0644)

答案 2 :(得分:2)

您应该能够使用以下方法在文件上设置这些权限(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()