Changing system file permission

2019-02-25 10:54发布

问题:

I've really tried everything:

  • NetHackFileHelpers
  • How to get File Permission Mode programmatically in Java
  • Change file permission in application
  • Mount R/W system in android application to edit Read Only files

Now, suppose I've remounted as root, and therefore RW permission on file system (Android version 2.3.7):

Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes("chmod -c 0777 /system/etc/customization/settings/com/android/browser/custom_settings.xml\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();

or:

Process process = Runtime.getRuntime().exec("su -c \"/system/etc/customization/settings/com/android/browser/custom_settings.xml\"");

or:

Class<?> fileUtils = Class.forName("android.os.FileUtils");
            Method setPermissions =
                fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class);
            int a = (Integer) setPermissions.invoke(null, "/system/etc/customization/settings/com/android/browser/custom_settings.xml", 0777, -1, -1);

The behaviour is the same: nothing happens. Whereas if I chmod from adb shell works fine. How can I change the permissions of that file from within my code?

回答1:

Here is my solution:

        Process sh = Runtime.getRuntime().exec("su", null, new File("/system/bin/"));
        OutputStream os = sh.getOutputStream();

        os.write(("chmod 777 <filepath>").getBytes("ASCII"));
        os.flush();
        os.close();
        sh.waitFor();