How to set rw- r— r— permissions programmatically?

2020-02-28 23:39发布

I am developing an application that can restore apps' data back to /data/data/{packageName}. After restoring the files, I am setting the permissions to rw- r-- r--. I set it in this way:

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

and calling chmod(file, 644);

But when I check these files' permissions in file explorer it shows me "--- rwx r-x".

So how can I set the permissions to rw- r-- r--?

3条回答
Rolldiameter
2楼-- · 2020-02-29 00:10

The value is wrong, the correct one is 420 (420 decimal is 644 octal). Alternatively you can add a leading 0 to make it a java octal literal. i.e.

chmod(destinationFile, 0644)
查看更多
在下西门庆
3楼-- · 2020-02-29 00:27

You should be able to set these permissions (rw- r-- r--) on the file using:

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

where path is your File object.

You shouldn't need to use FileUtils with reflection to set permissions on a file. You can just use the helper methods on the File class. With File, you can also call: setReadable(), setWritable(), and setExecutable()

查看更多
该账号已被封号
4楼-- · 2020-02-29 00:28
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) {
    }
}
查看更多
登录 后发表回答