问题分析
IO发生异常时抛出,引起的原因很多,如相关文件不存在、无权限读写、编码错误、文件读到末尾、IO中断、JSON、URL等格式不正确等。
解决方案
引起IO异常的原因很多,如相关文件不存在、无权限读写、编码错误、文件读到末尾、IO中断、JSON、URL等格式不正确等。建议捕获IO异常并做相应的业务处理。
代码示例
示例一
java.io.IOException: open failed: EACCES (Permission denied)
确认文件路径,增加读写外部存储上的文件权限:
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
示例二
java.io.IOException: open failed: ENOENT (No such file or directory)
增加try catch块做异常处理。
public void readFile(String filePath) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filePath));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
参考文献
https://developer.android.com/training/permissions/index.html (权限使用文档)
https://developer.android.com/reference/android/Manifest.permission.html (权限分类文档)
https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
https://developer.android.com/reference/java/io/IOException.html
https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous (普通权限及危险权限)
https://developer.android.com/training/permissions/requesting.html#perm-check (权限授权方式)
文档内容是否对您有帮助?