需權限:READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE (API 19+ 需動態申請)。
// 檢查掛載狀態
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dir = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!dir.exists()) dir.mkdirs();
File file = new File(dir, "data.txt");
// 寫入
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write("Hello SD Card".getBytes(StandardCharsets.UTF_8));
}
// 讀取
String content;
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buf = new byte[(int) file.length()];
fis.read(buf);
content = new String(buf, StandardCharsets.UTF_8);
}
}
注意:Android 10+ (API 29) 採用分區儲存,建議改用 MediaStore 或 getExternalFilesDir() (免權限、隨 App 卸載刪除)。
無需權限,App 卸載自動清除。路徑:/data/data/package.name/files/
// 寫入
try (FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE)) {
fos.write("Hello Internal".getBytes());
}
// 讀取
String content;
try (FileInputStream fis = openFileInput("data.txt")) {
byte[] buf = new byte[fis.available()];
fis.read(buf);
content = new String(buf);
}
放置預設資料庫、字體、設定檔等唯讀資源。
// 讀取 assets/config.json
String json;
try (InputStream is = getAssets().open("config.json")) {
byte[] buf = new byte[is.available()];
is.read(buf);
json = new String(buf, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// 取得外部儲存總量/可用量
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSizeLong();
long totalBlocks = stat.getBlockCountLong();
long availBlocks = stat.getAvailableBlocksLong();
long totalSize = blockSize * totalBlocks;
long availSize = blockSize * availBlocks;
// 格式化顯示
String totalStr = Formatter.formatFileSize(this, totalSize);
String availStr = Formatter.formatFileSize(this, availSize);
Context.getFilesDir()、getCacheDir()、getExternalFilesDir() 取代硬編碼路徑。try-with-resources 自動關閉流,防止洩漏。