把資料固化到檔案裡是開發中很常遇到的需求。下面整理兩種寫法:標準 Java 的文件輸出流,以及 Android 開發中透過 Context 寫入內部儲存。文中只列核心程式碼。
try {
File file = new File("mnt/sdcard/newfile.txt"); // 先建立檔案
FileOutputStream fos = new FileOutputStream(file); // 再建立輸出流
String content = name + ":" + pwd; // 要寫入的內容:使用者名稱、冒號、密碼
fos.write(content.getBytes()); // write 只能接受位元組,所以要 getBytes
fos.flush(); // 清空緩衝
fos.close(); // 關閉輸出流
}
catch (Exception e) { // 有風險,必須 try-catch
e.printStackTrace();
}
這是最通用的寫法,輸出流可以直接建立。但在 Android 開發中,若要把檔案寫進 ROM 內部儲存空間,這種方式就不太好用,通常得改用 Context 的方法。
public class savepwd {
private Context context;
public savepwd(Context context) { // 建構時注入並初始化 Context
this.context = context;
}
public void saveToRom(String name, String pwd) {
try {
// 用 Context 的 openFileOutput 建立輸出流
FileOutputStream fos = context.openFileOutput("config.txt", Context.MODE_PRIVATE);
String content = name + ":" + pwd; // 要寫入的內容
fos.write(content.getBytes());
fos.flush();
fos.close();
}
catch (Exception e) {
Toast.makeText(context, "ROM 檔案寫入失敗", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
兩者的差異在於檔案落在哪裡:openFileOutput 寫到應用程式的私有目錄,不需要任何權限,卸載時會一起清掉;而寫到 mnt/sdcard 這類外部儲存,則需要宣告 WRITE_EXTERNAL_STORAGE 權限並處理版本差異。另外,若只是保存少量設定,SharedPreferences 會比自建檔案更省事。