java - 防止应用程序从 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 消息或执行某些操作。
解决方案
在清单文件中添加此属性:
android:installLocation="preferExternal"
推荐阅读
- python - 如何从熊猫中所有列的字符串中提取数字并取数字的中位数?
- javascript - 如何在 discord.js 中创建播放命令?
- java - 不支持 HTTP 405 请求方法“PUT”
- node.js - 服务器端多个文档(txt、doc、pdf、png、xls)转换为pdf
- python-3.x - 用python除法
- postgresql - org.postgresql.util.PSQLException:在此 ResultSet 中找不到列名 finance_finance_id
- c++ - C ++调用返回成员函数输出“?初始化之前”
- dax - ABS 值的 Power BI 计算列
- python - 为什么即使我将这些值作为字符串类型插入,tkinter 项目中的数字值也是整数而不是字符串?
- javascript - react-native 中如何调用 props.children 中组件的函数?