首页 > 解决方案 > 防止应用程序从 java.io.IOException 崩溃:写入失败:ENOSPC(设备上没有剩余空间)

问题描述

在尝试写入设备时,当设备已满时,我收到错误: 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 消息或执行某些操作。

标签: javaandroidioexception

解决方案


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

android:installLocation="preferExternal"

推荐阅读