Reading or writing a file in /data on a rooted Android device

▼魔方 西西 提交于 2019-12-10 09:31:11

问题


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.

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.

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.

Thank you,


回答1:


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.

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.

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.

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.

Source: How-To SU




回答2:


Through coding you can add up a line like

Runtime.getRuntime().exec("chmod 077" +your_file_you_need_to_give_permission); 


来源:https://stackoverflow.com/questions/5271879/reading-or-writing-a-file-in-data-on-a-rooted-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!