首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 非 Activity 類創建內部文件:傳遞 Context 獲取 FileOutputStream

     編輯:程式設計綜合問答

問題

openFileOutput() 是 Context 方法,非 Activity 類中無法直接調用。

解決方案:傳遞 Context 參數


// 工具類
public class FileUtils {
    public static void writeToFile(Context context, String filename, String content) {
        FileOutputStream fos = null;
        try {
            // 關鍵:context.openFileOutput()
            fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
            fos.write(content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            Log.e("FileUtils", "Write failed", e);
        } finally {
            if (fos != null) {
                try { fos.close(); } catch (IOException ignored) {}
            }
        }
    }

    public static String readFromFile(Context context, String filename) {
        StringBuilder sb = new StringBuilder();
        try (FileInputStream fis = context.openFileInput(filename);
             InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            Log.e("FileUtils", "Read failed", e);
        }
        return sb.toString();
    }
}

調用示例


// Activity 中
FileUtils.writeToFile(this, "myFile.txt", "Hello World");

// Fragment 中
FileUtils.writeToFile(requireContext(), "myFile.txt", "Hello World");

// Service / BroadcastReceiver 等任何 Context 子類
FileUtils.writeToFile(getApplicationContext(), "myFile.txt", "Hello World");

進階:封裝為擴展函數


// FileUtils.kt
fun Context.writeInternalFile(filename: String, content: String) {
    openFileOutput(filename, MODE_PRIVATE).use { it.write(content.toByteArray()) }
}

fun Context.readInternalFile(filename: String): String {
    return openFileInput(filename).bufferedReader().use { it.readText() }
}

// 使用極其簡潔
this.writeInternalFile("config.json", jsonString)
val json = this.readInternalFile("config.json")

關鍵點總結

  1. 內部存儲綁定 Context:Context.openFileOutput() 創建的文件私有於該應用,路徑 /data/data/pkg/files/
  2. 任何 Context 子類均可:Activity、Service、Application、BroadcastReceiver 等
  3. 避免傳遞 Application Context 給 UI 相關操作:文件操作無 UI,傳 ApplicationContext 更安全 (生命周期最長)
  4. MODE_PRIVATE (0) 覆蓋模式:同名文件會被截斷重寫
  5. 大文件/頻繁讀寫考慮:BufferedOutputStream、MappedByteBuffer、或遷移至 Room/DataStore

現代替代:DataStore (Jetpack)


// Preferences DataStore (鍵值對)
val Context.dataStore: DataStore by preferencesDataStore(name = "settings")

// 寫入
suspend fun Context.saveToken(token: String) {
    dataStore.edit { it.putString("token", token) }
}

// 讀取 (Flow)
val tokenFlow: Flow = context.dataStore.data
    .map { prefs -> prefs.getString("token") ?: "" }

優點:異步、事務性、遷移自動、協程整合、主線程安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved