【发布时间】:2012-12-16 18:28:54
【问题描述】:
澄清:由于来自 Eclipse 的消息,我什至无法编译。第一个代码 sn -p:input 和 inputBuffer 无法识别。第二个代码sn -p,Eclipse要我切换开关“Compliance and JRE to 1.7”
我是 try-with-resources 的新手,我不太理解语法或我做错了什么。这是我的代码
try {
FileReader input = new FileReader(this.fileName);
BufferedReader inputBuffer = new BufferedReader (input);
String line;
while ((line = inputBuffer.readLine()) != null) {
String[] inputData = line.split(",");
Node<Integer> newNode = new Node<Integer>(Integer.parseInt(inputData[0]),
Integer.parseInt(inputData[1]));
this.hashMap.add(newNode);
}
//inputBuffer.close();
//input.close();
}catch (NumberFormatException nfe){
System.out.println(
"Repository could not load data due to NumberFormatException: " + nfe);
}catch (FileNotFoundException fnfe) {
System.out.println("File not found, error: " + fnfe);
}finally {
inputBuffer.close();
input.close();
}
finally块不起作用,所以我想试试
try (FileReader input = new FileReader(this.fileName)) {
......
}catch (FileNotFoundException e) {
......
}finally {
inputBuffer.close();
input.close();
}
然而
我还应该将 BufferedReader 添加到
try (...)... 但是如何?这还需要我将“Compliance and JRE to 1.7”切换。到目前为止,我不知道这意味着什么以及这将如何影响我的程序,在有人解释这一切意味着什么或者我做错了什么之前,我不愿意这样做。
编辑
我在 try 块之前移动了声明并用 null 初始化,这“ok”吗?
FileReader input = null;
BufferedReader inputBuffer = null;
try {
input = new FileReader(this.fileName);
inputBuffer = new BufferedReader (input);
...
} ...
【问题讨论】:
-
你有一些堆栈跟踪吗?
-
我还没有编译。问题在于来自 Eclipse 的错误消息。在第一个示例中,
input.close()无法识别input,因为它位于 try 块中。在第二个示例中,我收到另一条系统消息。 -
如果你有 try 块,不管 finally 总是有异常或无异常执行。你得到什么错误并使用 fnfe.printStackTrace();
-
如果您对新的“使用资源尝试”不满意,旧的方法很好。欲了解更多信息..在下面查看我的答案