2012-09-11 42 views
0

有什麼方法可以在根目錄(例如/ data /)上編寫和讀取紮根Android手機上的文本文件?安卓在根目錄下打開文件

InputStream instream = openFileInput("/data/somefile"); 

不起作用

回答

1

爲了能夠做到你要求你必須通過SU二進制操作所有的東西。

像...

try { 
     Process process = Runtime.getRuntime().exec("su"); 
     process.waitFor(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

閱讀會更容易然後寫,寫最簡單的是將文件寫入到一些地方,其中u使用標準的Java API的訪問,然後將其移動到新位置使用su二進制。

2

您只能訪問/ data文件夾,您是root用戶。

呼叫到SU二進制和寫入字節(這些字節的指令)在通過的OutputStream SU二進制,並通過InputStream讀入命令的輸出,很容易:
電話cat命令來讀取文件。

try { 
    Process process = Runtime.getRuntime().exec("su"); 
    InputStream in = process.getInputStream(); 
    OutputStream out = process.getOutputStream(); 
    String cmd = "cat /data/someFile"; 
    out.write(cmd.getBytes()); 
    out.flush(); 
    out.close(); 
    byte[] buffer = new byte[1024 * 12]; //Able to read up to 12 KB (12288 bytes) 
    int length = in.read(buffer); 
    String content = new String(buffer, 0, length); 
    //Wait until reading finishes 
    process.waitFor(); 
    //Do your stuff here with "content" string 
    //The "content" String has the content of /data/someFile 
} catch (IOException e) { 
    Log.e(TAG, "IOException, " + e.getMessage()); 
} catch (InterruptedException e) { 
    Log.e(TAG, "InterruptedException, " + e.getMessage()); 
} 

不要使用OutputStream中寫入文件,OutputStream用於執行SU二進制文件內的命令,並且InputStream用於get命令的輸出。