Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 檔案存取:儲存到應用私有空間與 SD 卡

編輯:關於 Android 程式設計

以下整理 Android 中把資料存檔到應用內部與 SD 卡的常用寫法。

首先是權限宣告:

1.權限添加  

接著是一組檔案讀寫的工具方法:

public static String getDataFolderPath(Context paramContext) { return Environment.getDataDirectory() + "/data/" + paramContext.getPackageName() + "/files"; } public static String getMyFileDir(Context context){ return context.getFilesDir().toString(); } public static String getMyCacheDir(Context context){ return context.getCacheDir().toString(); } /** @desc 保存內容到文件中 */ public static void save(Context context, String fileName, String content, int module) { try { FileOutputStream os = context.openFileOutput(fileName, module); os.write(content.getBytes()); os.close(); } catch (Exception e) { e.printStackTrace(); } } /** @desc 讀取文件內容 */ public static String read(Context context, String fileName){ try { FileInputStream fis = context.openFileInput(fileName); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = 0; while((len = fis.read(b)) != -1){ bos.write(b, 0, len); } byte[] data = bos.toByteArray(); fis.close(); bos.close(); return new String(data); } catch (Exception e) { e.printStackTrace(); } return null; } /** @desc 將文本內容保存到 sd 卡的文件中 */ public static void saveToSDCard(Context context, String fileName, String content) throws IOException{ File file = new File(Environment.getExternalStorageDirectory(),fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(content.getBytes()); fos.close(); } /** @desc 讀取 sd 卡文件內容 */ public static String readSDCard(String fileName) throws IOException { File file = new File(Environment.getExternalStorageDirectory(),fileName); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } byte[] data = bos.toByteArray(); fis.close(); bos.close(); return new String(data); }

讀寫應用內部檔案時,用 openFileOutput / openFileInput 搭配不同的 mode;而存到 SD 卡時,則直接以 Environment.getExternalStorageDirectory() 取得路徑,再用 FileOutputStream 與 FileInputStream 處理。別忘了在 manifest 補上 WRITE_EXTERNAL_STORAGE 權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved