Android Studio 檔案讀寫

 Android Studio 檔案讀寫

讀寫權限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

取得儲存路徑

  • getDataDirectory()
    • 取得手機內存根目錄
  • getDownloadCacheDirectory()
    • 取得手機暫存
  • getRootDirectory()
    • 取得手機系統目錄
  • getExternalStorageDirectory()
    • 取得手機外部儲存SD Card目錄

取得路徑的格式

  • getPath()
    • 取得定義的路徑
  • getAbsolutePath()
    • 取得絕對路徑
  • getCanonicalPath()
    • 取得符合路徑規範的路徑

File file = new File("TXT/./test.txt");
Log.d("frilgetPath","=="+file.getPath());
Log.d("frilAbsolutePath","=="+file.getAbsolutePath());
Log.d("frilCanonicalPath","=="+file.getCanonicalPath());

結果如下
      
D/frilgetPath: ==TXT/./test.txt
D/frilAbsolutePath: ==/TXT/./test.txt
D/frilCanonicalPath: ==/TXT/test.txt

Text讀取

try{
FileReader fw = new FileReader(Environment.getExternalStorageDirectory().getAbsolutePath()+"/TXT/T.txt");
BufferedReader bw = new BufferedReader(fw); //BufferedWeiterFileWrite物件做連結
String thisLine ;//獲得讀取的每行資料
String txtshow = "";
while ((thisLine = bw.readLine()) != null) {
txtshow = txtshow + thisLine +"\n\r";
}
txt.setText(txtshow);//使用TextView承接
bw.close();

}catch(IOException e){
e.printStackTrace();
}

Text寫檔

try{
File storage = Environment.getExternalStorageDirectory();
File file = new File(storage, "TXT");
if (! file.exists())//判斷檔案是否存在
{
file.mkdir();//建立檔案
}
File newTextFile = new File(storage.getPath() + "/TXT" ,"T.txt");

if (! newTextFile.exists())
{
newTextFile.createNewFile();//建立文件
}
FileWriter fw = new FileWriter(newTextFile,true);//(檔案位置, 是否接續寫入)
BufferedWriter bw = new BufferedWriter(fw); //BufferedWeiterFileWrite物件做連結
bw.write(editText.getText().toString());//寫入EditText的資料
bw.newLine();
bw.close();
}catch(IOException e){
e.printStackTrace();
}

額外參考

留言