2011-12-08 86 views
0

我有問題。我使用名爲test.txt的代碼文本文件創建了一個名爲test.txt的文件,然後使用cat命令從系統文件中獲取文本,並將此文本放到我的test.txt中,但我不知道如何從此文件讀取文本。我需要從這個文件讀取文本,然後將其保存到我的SharedPreferences。 這裏是代碼:如何從SD卡文件讀取文本?

try { 
      FileOutputStream fos = new FileOutputStream("/sdcard/test.txt"); 
      DataOutputStream dos = new DataOutputStream(fos); 
      dos.flush(); 
      dos.close(); 
     } catch (FileNotFoundException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

Process a; 
     try { 
      a = Runtime.getRuntime().exec("su"); 

      DataOutputStream aaa = new DataOutputStream(a.getOutputStream()); 
      aaa.writeBytes("cat /proc/sys/sad/asdsad > /sdcard/test.txt\n"); 
      aaa.writeBytes("exit\n"); 
      aaa.flush(); 
      try { 
       a.waitFor(); 
       if (a.exitValue() != 255) { 
        // TODO Code to run on success 
        toastMessage("root"); 
        } 
       else { 
        // TODO Code to run on unsuccessful    
        toastMessage("not root"); 
        } 
      } catch (InterruptedException e) { 
       // TODO Code to run in interrupted exception  
       toastMessage("not root"); 
       } 
     } catch (IOException e) { 
      // TODO Code to run in input/output exception 
      toastMessage("not root"); 
      } 

回答

3

你並不需要「複製」文件,以便閱讀SD卡。

無論如何,使用「貓」進行復制並不是你想要的應用程序。當你放棄對操作的全部控制時,錯誤檢測和處理變得更加困難。

只需使用FileReaderBufferedReader。一個例子可以發現here。這裏是一個副本:

File file = new File("test.txt"); 
StringBuffer contents = new StringBuffer(); 
BufferedReader reader = null; 

try { 
    reader = new BufferedReader(new FileReader(file)); 
    String text = null; 

    // repeat until all lines is read 
    while ((text = reader.readLine()) != null) { 
     contents.append(text) 
      .append(System.getProperty(
       "line.separator")); 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (reader != null) { 
      reader.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
}   

Log.e("TEXT", contents.toString()); 

所有這些都是非常基本的東西。你應該考慮閱讀一些Java相關書籍或一些文章。

+0

是的,我知道這段代碼,我很瞭解基本編程,但是最近我開始在Android中編程,所以我不知道Java中的所有命令。我的問題是,我不知道如何使用cat命令將系統文件中的文本保存到共享首選項。第一種更簡單的方法是直接將系統文件中的文本放到我的SharedPreferences中,但我不知道如何製作它。或者通過使用cat創建一些文件獲取文本,將文本放入此文件,然後將創建文件中的文本放到SharedPreferences中。 – Adam