在根目录下的Android设备上在/data中读取或写入文件 [英] Reading or writing a file in /data on a rooted Android device
问题描述
我正在尝试以编程方式在有根电话上的/data目录中读取/写入文件. 首先,我执行 shell执行 su ,以确保我的程序具有超级用户访问权限,并且运行正常.
I am trying to programmatically read/write a file in /data directory on a rooted phone. I first shell execute su to make sure my program gets super user access, which works fine.
我可以通过程序内的shell execs 命令在/data中读取/写入文件,但是在以下情况下,我收到"权限被拒绝" java.io.IOException使用Android File或其他API.
I am able to read/write files in /data thru shell execs commands inside my program, but I am getting "Permission denied" java.io.IOException when using Android File or other APIs.
如何使用API在有根电话上读取/写入/data?显然,像Root Explorer之类的程序可以做到这一点.
How to use the APIs to read/write to /data on a rooted phone ? this is obviously possible as programs such as Root Explorer does it.
谢谢
推荐答案
简而言之,不能,通过API不能严格,因为您需要确保修改命令的运行方式为root,否则操作系统将拒绝这些操作.
In short, no, this is not strictly possible through the API's as you need to make sure that your modification commands as run as root, or else the OS will reject those operations.
您需要将修改命令传递给su
命令,以使其以root身份执行.
Chainfire在他的 github 上提供一个示例实现 Shell
类,可用于以root用户身份执行rm
命令或任何其他命令.
You need to pipe the modification commands to the su
command in order for it to execute as root.
On his github, Chainfire provides a sample implementation of a Shell
class that you can use to execute rm
commands, or any other command, as root.
以编程方式可以执行此操作的一种方法是将要编辑的文件复制到临时目录(例如/sdcard/tmp.txt
),然后编辑该文件,然后将其复制回原始位置并覆盖该位置.
One way that you could do it programmatically would be do copy the file you are trying to edit to a temporary directory, say /sdcard/tmp.txt
, and edit that file, then copy it back to the original location and overwrite the one there.
另一种方法是chmod
目标文件(即chmod 777 /data/xxx.txt
),以便您可以以编程方式读取/写入其内容.这就是为什么出现Permission denied
错误的原因,因为您的程序无权访问其他文件.此处的关键是您需要确保将chmod
命令本身通过管道传递到su
命令中,以便不会拒绝THAT命令.我建议您阅读下面链接中的指南,因为它非常详尽地介绍了如何处理需要以root身份运行的情况.
Another way would be to chmod
the target file (ie chmod 777 /data/xxx.txt
) so that you can read/write its contents programmatically. That is why you are getting the Permission denied
error because your program does not have permission to access to other files. The key here is that you need to make sure that the chmod
command itself is piped into the su
command so that THAT command does not get denied. I would suggest reading the guide in the link below as it is very thorough in how you can approach situations where running as root is necessary.
来源:操作方法SU
这篇关于在根目录下的Android设备上在/data中读取或写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!