澄清:由于来自 Eclipse 的消息,我什至无法编译。第一个代码片段:input
并且inputBuffer
无法识别。第二个代码片段,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);
...
} ...