2018/10/18

[Android] Read & Write Text File

在Android app 讀取&寫入文字檔的方法。

在AndroidManifest.xml要打開app寫入及讀取的權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

讀取
private String ReadStringFile(String dir, String filename){
    StringBuilder text = new StringBuilder();
    try {
        File file = new File(Environment.getExternalStorageDirectory() + dir, filename);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            text.append(line);
        }
        br.close() ;
    }catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "can't find" + dir + filename, Toast.LENGTH_LONG).show();
    }
    Log.d(TAG,"read file-" + dir + filename + ":" + text);
    return text.toString();
}

寫入
private void WriteStringFile(String data, String dir, String filename) {
    File file = new File(Environment.getExternalStorageDirectory() + dir, filename);
    FileOutputStream stream = null;
    try {
        stream = new FileOutputStream(file);
        stream.write(data.getBytes());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

在手機中建立一個myDoc資料夾,裡面放一個file.txt文字檔
程式碼讀取檔案的路徑寫法如下:
private String str = "";
private static String text_filepath = "/myDoc/";
private static String text_filename = "file.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    str = ReadStringFile(text_filepath, text_filename); // read txt file
    WriteStringFile("Hello", text_filepath, text_filename); // write "Hello" into txt file
}

End

沒有留言:

張貼留言