在Java中使用try with resources时出错
我有这个方法,我正在使用JavaSE7的try资源在Java中使用try with resources时出错,java,try-catch-finally,finally,try-with-resources,Java,Try Catch Finally,Finally,Try With Resources,我有这个方法,我正在使用JavaSE7的try资源 private void generateSecretWord(String filename){ try (FileReader files = new FileReader(filename)){ Scanner input = new Scanner(files); String line = input.nextLine(); String[] w
private void generateSecretWord(String filename){
try (FileReader files = new FileReader(filename)){
Scanner input = new Scanner(files);
String line = input.nextLine();
String[] words = line.split(",");
Collections.shuffle(Arrays.asList(words));
if (words[0].length()>1){
secretWord = words[0];
return;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (files!=null) files.close();
}
}
我在最后
块中得到编译错误,文件无法解析为变量
我有try with block
中文件的参考。为什么会出现此错误以及如何修复它
谢谢当您使用try with资源时,您不需要显式关闭它们。try with resources将负责关闭这些资源 基于 try with resources语句是声明一个或多个资源的try语句。资源是一个必须在程序完成后关闭的对象。try with resources语句确保在语句末尾关闭每个资源 摘自(14.20.3): try with resources语句使用变量(称为资源)进行参数化,这些变量在try块执行之前初始化,并在try块执行之后以与初始化顺序相反的顺序自动关闭。当资源自动关闭时,catch子句和finally子句通常是不必要的 ResourceSpecification使用初始值设定项表达式声明一个或多个局部变量,作为try语句的资源
因此,您不再需要关闭资源。Try with resources会自动为您执行此操作,并且您的
文件阅读器将仅在Try
块中可用。因此会出现编译错误。因为没有其他人提到过这一点,如果您想手动处理它,可以执行以下操作:
private void generateSecretWord(String filename){
FileReader files = null;
try {
files = new FileReader(filename);
Scanner input = new Scanner(files);
String line = input.nextLine();
String[] words = line.split(",");
Collections.shuffle(Arrays.asList(words));
if (words[0].length()>1){
secretWord = words[0];
return;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (files!=null)
files.close();
}
}
您试图执行的代码是Java7之前的老式代码,在Java7中必须关闭资源以避免内存泄漏。但是在新的Java 7中,要灵活地使用它,即使无法访问它,也不需要关闭资源。在Pom.xml中将Java设置为1.7或更高版本
如下:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
UTF-8
1.8
1.8
1.8
这是否意味着不需要最终
块,或者不需要仅关闭文件
needed@user2708477这意味着关闭资源不需要finally
块。如果您需要做其他事情,即使发生异常
也不能跳过,那么您仍然需要最终
块。但是,如果您只是想确保文件在任何情况下都将被关闭,那么您不需要这样做,因为这是隐式完成的。