简体   繁体   中英

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

In an attempt to write to the device, when the device is full, I am getting error: com.google.gson.JsonIOException: java.io.IOException: write failed: ENOSPC (No space left on device) . I have a try-catch block to catch an IOException and a few lines to check the size of the list and storage space available to determine if there is space to write the file but yet it still crashed the app and I got the IOException mentioned above.

Here is the code:

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();
    }
}

Is there a way to stop the app from crashing and just display a Toast message to the user or perform some action.

在您的清单文件中添加此属性:

android:installLocation="preferExternal"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM