+-

在 Java中,可能很容易需要做一些事,例如实例化BufferedWriter对象.这可以通过以下方式完成:
File outFile = new File("myTestFile.txt");
BufferedWriter w = null;
try { w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); }
catch (FileNotFoundException|UnsupportedEncodingException e) { System.out.println(e.getMessage()); }
w.write("Test string");
w.newLine();
请注意,在try-catch块之前声明了w.这样可以在try-catch之后使用变量处于适当的范围之内.它使用空指针初始化,否则像netbeans这样的IDE会警告该变量可能尚未分配.但是,IDE仍然抱怨当您到达w.write()时,w可能具有空值.这很合理,因为try块可能会失败!
有没有更优雅,更明智的方法来执行此操作,而不会导致逻辑问题(如我的IDE提醒我的那样)?
我意识到我可以将w所做的所有事情包装在try块中,但这对我的任务不可行.如果还有其他选择,我还可以如何初始化w?
谢谢!
最佳答案
如果您使用的是Java 7,请考虑使用 try-with-resources.
try (BufferedWriter w = new BufferedWriter
(new OutputStreamWriter(
new FileOutputStream(outFile), "utf-8"))) {
w.write("Test string");
w.newLine();
} catch (IOException ex) {
ex.printStackTrace();
}
如果您的问题是try块中的代码量,请考虑将该代码分解为方法.
try (BufferedWriter w = new BufferedWriter
(new OutputStreamWriter(
new FileOutputStream(outFile), "utf-8"))) {
writeEverythingINeed(w);
} catch (IOException ex) {
ex.printStackTrace();
}
另外,您别无选择,只能将其余语句括在if中.
BufferedWriter w = null;
try { w = ... }
catch (FileNotFoundException | UnsupportedEncodingException e) {
System.out.println(e.getMessage());
}
if (w != null) {
w.write("Test string");
w.newLine();
}
同样,if内的块可以重构为方法.
点击查看更多相关文章
转载注明原文:java-如何正确地给对象赋值,对象的赋值会引发异常 - 乐贴网