从一本 Java 书籍中发现了以下代码
public void writeFile(String fileName, String content){
File file = new File(fileName);
try {
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
}
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
上面的代码没有任何问题,我根本看不出嵌套try没有定义内部 catch 块的意义。或者这样做有什么我错过的目的吗?
修改后的代码:
public void writeFile(String fileName, String content){
File file = new File(fileName);
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
大话西游666
相关分类