gpt4 book ai didi

java - 关闭文件读/写操作的正确异常处理

转载 作者:行者123 更新时间:2023-11-30 06:13:19 24 4
gpt4 key购买 nike

我想要的是减少从方法中抛出的异常。
如您所见,我在外部 catch block 中有一个内部 try catch 以避免抛出异常。
这是执行此操作的常规方法还是有更好(更优雅)的方法?
还是这种方法完全错误,我应该抛出异常?

public static String readText(String filename) {        
String text = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return text;
}

最佳答案

就我个人而言,我会选择使用 Files.readAllLines();Files.lines(); 的更现代的方法。

然后您需要处理的只是一个 IOException,系统会自动为您清理资源。

关于java - 关闭文件读/写操作的正确异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com