在 Java 中对资源使用 try 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20154312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:33:04  来源:igfitidea点击:

error while using try with resources in Java

javatry-catch-finallyfinallytry-with-resources

提问by brain storm

I have this method where I am using try with resources of Java SE 7.

我有这个方法,我在尝试使用 Java SE 7 的资源。

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(); 
        }

    }

I get compile error in finallyblock that files cannot be resolved to a variableI have reference for files in the try with block. why do I get this error and how to fix it?

我在finally块中收到编译错误,files cannot be resolved to a variable我对try with block. 为什么会出现此错误以及如何解决?

Thanks

谢谢

采纳答案by noone

Taken from the Java Language Spec(14.20.3):

摘自Java 语言规范(14.20.3):

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block. catch clauses and a finally clause are often unnecessarywhen resources are closed automatically.

A ResourceSpecification declares one or more local variables with initializer expressions to act as resources for the try statement.

try-with-resources 语句使用变量(称为资源)进行参数化,这些变量在 try 块执行之前初始化并在 try 块执行之后按照与它们初始化的相反顺序自动关闭。当资源自动关闭时,catch 子句和finally 子句通常是不必要的

ResourceSpecification 声明一个或多个带有初始化表达式的局部变量作为try 语句的资源。

So you do not need to close the Resource anymore. Try-with-resources does it automatically for you and your FileReaderwill only be available in the tryblock. Thus you get that compile error.

所以你不需要再关闭资源了。Try-with-resources 会自动为您执行此操作,并且您FileReader只能在该try块中使用。因此你会得到那个编译错误。

回答by kosa

When you are using try with resources you don't need to explicitly close them. try-with-resources will take care of closing those resources.

当您对资源使用 try 时,您不需要明确关闭它们。try-with-resources 将负责关闭这些资源。

Based on try-wtih-resource document

基于try-wtih-resource 文档

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

try-with-resources 语句是一种声明一个或多个资源的 try 语句。资源是程序完成后必须关闭的对象。try-with-resources 语句确保每个资源在语句结束时关闭。

回答by Michael Carver

Since no-one else has mentioned this, if you want to handle it manually you could do something like:

由于没有其他人提到过这一点,如果您想手动处理它,您可以执行以下操作:

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(); 
        }

    }

回答by Amit khandelwal

The code that you are trying to execute is old fashioned code before Java 7 where have to close the resources to avoid memory leaks. But in New Java 7 take it smartly and it is not necessary to close the resources even it is not accessible to finally block.

您尝试执行的代码是 Java 7 之前的老式代码,必须关闭资源以避免内存泄漏。但是在 New Java 7 中,要明智地使用它,即使无法访问 finally 块,也没有必要关闭资源。