分析:Android默认是无法直接操作/data目录的,只能读写程序自己的私有目录,也就是/data/data/package name/下,默认只能操作这个目录下的文件,也就是我们想直接读写/data是做不到的。
但是只要我们修改了/data目录下的目标文件的权限就可以进行操作了。
example:在/data/sibon/var目录下创建一个dir.ip文件,将输入的数据存储到dir.ip文件中。
1,修改权限(目标文件夹)
initChmod("chmod 777 /data/sibon/var");
/**修改文件或文件夹的权限**/
private void initChmod(String command){
Process process = null;
DataOutputStream os = null;
try{
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutpputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
}catch(Exception e){
}finally{
try{
if(os != null){
os.close();
}
process.destory();
}catch(Exception e){
}
}
}
2,进行写文件操作
saveText("start saveText now......");
/**向dir.ip中写入数据**/
private void saveText(String string){
File file = new File("/data/sibon/var/dir.ip");
BufferedWriter bw = null;
try{
//第二个参数的意义是说是否可以以append的方式添加数据
bw = new BufferedWriter(new FileWriter(file,false));
bw.write(string);
bw.flush();
System.out.println("写入数据成功");
}catch(Exception e){
e.printStackTrace();
}
}
3,修改dir.ip的权限(让其可读可写)
initChmod("chmod 666 /data/sibon/var/dir.ip");
4,(验证是否可以读取dir.ip中的数据)
readTxtFile(String filePath);
/**读取txt文本数据(一行一行的读取)**/
private static String readTxtFile(String strFilePath){
String path = strFilePath;
String context = "";//文本内容字符串
//打开文件
File file = new File(path);
//如果path是传递过来的参数,可以做一个非目录的判断
if(file.isDirectory()){
System.out.println("-----------------");
}
else {
try{
InputStream is = new FileInputStream(file);
if(is != null){
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while((line = buffreader.readLine()) != null){
content += line + "\n";
}
is.close();
}
}
catch (java.io.FileNotFoundException e)
{
System.out.println("The File doesn't not exist.");
}
catch (IOException e)
{
System.out.println(""+ e.getMessage());
}
}
return content;
}
}
原标题:如何在安卓/data(而不是/data/data)目录下进行文件的读写操作
关键词: