android中通过代码实现文件权限修改

前提:

1.手机被root;
2.该app已经取得了root权限。

目的:

试图获得系统文件夹下的文件的读写权限。

实现:

我们要使用的命令是:
chmod -R 0777 xxx/xxx等系统目录或文件
命令解读:

在Unix和Linux的各种操作系统下,每个文件(文件夹也被看作是文件)都按读、写、运行设定权限。
读、写、运行三项权限可以用数字表示,就是r=4,w=2,x=1。所以,rw-r–r–用数字表示成644。
反过来说777就是rwxrwxrwx,意思是该登录用户(可以用命令id查看)、他所在的组和其他人都有最高权限。

执行该命令的方法是:
Runtime.getRuntime().exec();
实现的关键是:

首先要通过命令”su”切换到Root身份,然后才能执行“chmod”等具体命令。

代码实现:
方法1:
    public static boolean execCommand(String command) {
        boolean status = false;
        if (TextUtils.isEmpty(command)) {
            return status;
        }
        try {
            Process exec = Runtime.getRuntime().exec("su");
            OutputStream outputStream = exec.getOutputStream();
            outputStream.write(command.getBytes(Charset.forName("utf-8")));
            outputStream.write("\n".getBytes());
            outputStream.write("exit\n".getBytes());
            outputStream.flush();
            int waitFor = exec.waitFor();
            Log.e(TAG, "execCommand command:"+command+";waitFor=" + waitFor);
            if (waitFor == 0) {
                //chmod succeed
                status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "execCommand exception=" + e.getMessage());
            return false;
        }
        return status;
    }
方法2:
    public static boolean execCommand(String command) {
        boolean status = false;
        if (TextUtils.isEmpty(command)) {
            return status;
        }
        String fullCommand = "su"+"\n"+command;
        try {
            Process exec = Runtime.getRuntime().exec(fullCommand);
            int waitFor = exec.waitFor();
            Log.e(TAG, "execCommand command:"+command+";waitFor=" + waitFor);
            if (waitFor == 0) {
                //chmod succeed
                status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "execCommand exception=" + e.getMessage());
            return false;
        }
        return status;
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值