簡體   English   中英

防止應用程序從 java.io.IOException 崩潰:寫入失敗:ENOSPC(設備上沒有剩余空間)

[英]Prevent app from crashing from java.io.IOException: write failed: ENOSPC (No space left on device)

在嘗試寫入設備時,當設備已滿時,出現錯誤: com.google.gson.JsonIOException: java.io.IOException: write failed: ENOSPC (No space left on device) 我有一個 try-catch 塊來捕獲 IOException 和幾行來檢查列表的大小和可用的存儲空間以確定是否有空間來寫入文件,但它仍然使應用程序崩潰,我得到了上面提到的 IOException .

這是代碼:

File file = new File(getExternalFilesDir(null), fileName+".txt");
int file_size = Integer.parseInt(String.valueOf(file.length()/1024));
long storage_size = (getAvailableInternalMemorySize()/1024);
long list_size = listToWrite.toString().getBytes().length/1024;
long total_size = file_size + list_size;
if(total_size < storage_size) {
    try (Writer writer = new FileWriter(file, false)) {
        Gson gson = new GsonBuilder().create();
        gson.toJson(listToWrite, writer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有沒有辦法阻止應用程序崩潰並只向用戶顯示 Toast 消息或執行某些操作。

在您的清單文件中添加此屬性:

android:installLocation="preferExternal"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM