TShopping

標題: Android 平台的檔案讀寫方式 [打印本頁]

作者: woff    時間: 2013-12-5 23:20
標題: Android 平台的檔案讀寫方式
處理檔案是程式開發過程中常會碰到的問題,在 Android 平台上讀寫檔案的也是利用 Java 的 File、InputStream 以及 OutputStream 物件來達成。不過 Android 系統對 App 的使用空間與檔案操作有一套自己的管理方式,透過系統提供的 Context 與 Environment 物件可以讓開發人員快速的進行檔案的各種操作。


A. 使用的物件以及方法
B. 原理說明
type 參數如果為 null 時可取得擺放公開檔案的根目錄,如果 App 要擺放的檔案型態不屬於上述那幾類,也可以直接將檔案擺放在根目錄。


C. 使用方式

1. 將資料寫入內部儲存體的檔案中

(1) 將檔案存放在 getFilesDir() 目錄

//**** 方法一 ****//
//取得內部儲存體擺放檔案的目錄
//預設擺放路徑為 /data/data/[package.name]/files/
File dir = context.getFilesDir();

//在該目錄底下開啟或建立檔名為 "test.txt" 的檔案
File outFile = new File(dir, "test.txt");

//將資料寫入檔案中,若 package name 為 com.myapp
//就會產生 /data/data/com.myapp/files/test.txt 檔案
writeToFile(outFile, "Hello! 大家好");

...
  1. //writeToFile 方法如下
  2. private void writeToFile(File fout, String data) {
  3.     FileOutputStream osw = null;
  4.     try {
  5.         osw = new FileOutputStream(fout);
  6.         osw.write(data.getBytes());
  7.         osw.flush();
  8.     } catch (Exception e) {
  9.         ;
  10.     } finally {
  11.         try {
  12.             osw.close();
  13.         } catch (Exception e) {
  14.             ;
  15.         }
  16.     }
  17. }


  18. //**** 方法二 ****//
  19. FileOutputStream out = null;
  20. try {
  21.     //在 getFilesDir() 目錄底下建立 test.txt 檔案用來進行寫入
  22.     out = openFileOutput("test.txt", Context.MODE_PRIVATE);

  23.     //將資料寫入檔案中
  24.     out.write("Hello! 大家好\n".getBytes());
  25.     out.flush();
  26. } catch (Exception e) {
  27.     ;
  28. } finally {
  29.     try {
  30.         out.close();
  31.     } catch (Exception e) {
  32.         ;
  33.     }
  34. }
複製代碼
(2) 將檔案存放在 getCacheDir() 目錄

//取得內部儲存體擺放暫存檔案的目錄
//預設擺放路徑為 /data/data/[package.name]/cache/
File dir = context.getCacheDir();

//在該目錄底下開啟或建立檔名為 "test.txt" 的檔案
File outFile1 = new File(dir, "test.txt");

//也可以使用 File.createTempFile() 來建立暫存檔案
File outFile2 = File.createTempFile("test", ".txt", dir);

//將資料寫入檔案中,若 package name 為 com.myapp
//就會產生 /data/data/com.myapp/cache/test.txt 檔案
writeToFile(outFile1, "Hello! 大家好");

//會產生 /data/data/com.myapp/cache/test-[亂數].txt 檔案
writeToFile(outFile2, "Hello! 大家好");
2. 讀取內部儲存體中的檔案內容

//** 方法一 **//
//取得內部儲存體擺放檔案的目錄
//預設擺放目錄為 /data/data/[package.name]/
File dir = context.getFilesDir();

//開啟或建立該目錄底下檔名為 "test.txt" 的檔案
File inFile = new File(dir, "test.txt");

//讀取 /data/data/com.myapp/test.txt 檔案內容
String data = readFromFile(inFile);

...
  1. //readFromFile 方法如下
  2. private String readFromFile(File fin) {
  3.     StringBuilder data = new StringBuilder();
  4.     BufferedReader reader = null;
  5.     try {
  6.         reader = new BufferedReader(new InputStreamReader(
  7.                  new FileInputStream(fin), "utf-8"));
  8.         String line;
  9.         while ((line = reader.readLine()) != null) {
  10.             data.append(line);
  11.         }
  12.     } catch (Exception e) {
  13.         ;
  14.     } finally {
  15.         try {
  16.             reader.close();
  17.         } catch (Exception e) {
  18.             ;
  19.         }
  20.     }
  21.     return data.toString();
  22. }



  23. //** 方法二 **//
  24. FileInputStream in = null;
  25. StringBuffer data = new StringBuffer();
  26. try {
  27.     //開啟 getFilesDir() 目錄底下名稱為 test.txt 檔案
  28.     in = openFileInput("test.txt");

  29.     //讀取該檔案的內容
  30.     BufferedReader reader = new BufferedReader(
  31.                    new InputStreamReader(in, "utf-8"));
  32.     String line;
  33.     while ((line = reader.readLine()) != null) {
  34.        data.append(line);
  35.     }
  36. } catch (Exception e) {
  37.     ;
  38. } finally {
  39.     try {
  40.         in.close();
  41.     } catch (Exception e) {
  42.         ;
  43.     }
  44. }
複製代碼
3. 將資料寫入外部儲存體的檔案中

(1) 檢查外部儲存體的狀態是否可以讀寫
  1. //檢查外部儲存體是否可以進行寫入
  2. public boolean isExtStorageWritable() {
  3.     String state = Environment.getExternalStorageState();
  4.     if (Environment.MEDIA_MOUNTED.equals(state)) {
  5.         return true;
  6.     }
  7.     return false;
  8. }

  9. //檢查外部儲存體是否可以進行讀取
  10. public boolean isExtStorageReadable() {
  11.     String state = Environment.getExternalStorageState();
  12.     if (Environment.MEDIA_MOUNTED.equals(state) ||
  13.         Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
  14.         return true;
  15.     }
  16.     return false;
  17. }
複製代碼
(2) 將檔案存放在外部儲存體 (私有檔案)
  1. //將檔案存放在 getExternalFilesDir() 目錄
  2. if (isExtStorageWritable()){
  3.     File dir = context.getExternalFilesDir(null);
  4.     File outFile = new File(dir, "test.txt");
  5.     writeToFile(outFile, "Hello! 大家好");
  6. }

  7. //將檔案存放在 getExternalCacheDir() 目錄
  8. if (isExtStorageWritable()){
  9.     File dir = context.getExternalCacheDir();
  10.     File outFile = new File(dir, "test.txt");
  11.     writeToFile(outFile, "Hello! 大家好");
  12. }
複製代碼
(3) 將檔案存放在外部儲存體 (公開檔案)
  1. //取得存放公開圖片檔的目錄,並在該目錄下建立 subDir 子目錄
  2. public File getExtPubPicDir(String subDir) {
  3.     File file = new File(Environment.getExternalStoragePublicDirectory(
  4.             Environment.DIRECTORY_PICTURES), subDir);
  5.     //若目錄不存在則建立目錄
  6.     if (!file.mkdirs()) {
  7.         Log.e(LOG_TAG, "無法建立目錄");
  8.     }
  9.     return file;
  10. }
複製代碼
...
  1. //取得外部儲存體存放圖片公開檔案目錄底下的 flowers 子目錄
  2. File path = getExtPubPicDir("flowers");

  3. //在該目錄下建立檔名為 flower.jpg 的檔案
  4. File file = new File(path, "flower.jpg");

  5. //將圖片內容由 App 拷貝到該目錄下
  6. InputStream is = getResources().openRawResource(R.drawable.flower);
  7. OutputStream os = new FileOutputStream(file);

  8. byte[] buffer = new byte[1024];
  9. while (true) {
  10.     int bytesRead = in.read(buffer);
  11.     if (bytesRead == -1) break;
  12.     os.write(buffer, 0, bytesRead);
  13. }

  14. is.close();
  15. os.close();
複製代碼
4. 刪除檔案

當 App 被移除時,Android 系統會刪除所有由該 App 產生存放在內部儲存體的檔案,以及存放在外部儲存體的私有檔案 (Context.getExternalFilesDir() 目錄底下的檔案),不過最好還是在檔案不用時就將它刪除,以免佔用不必要的空間。
  1. //刪除暫存目錄中 test.txt 檔案
  2. File f = new File(context.getCacheDir(),"test.txt");
  3. f.delete();

  4. //刪除 getFilesDir() 目錄底下 test.txt 檔案
  5. context.deleteFile("test.txt");
複製代碼





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2