简体   繁体   English

询问try-with-resources语句

[英]Inquiry about try-with-resources statement

Just confirming that the following does not compile and it's not a mistake of mine: 只需确认以下内容无法编译,这不是我的错误:

try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
        {
        }
        catch(IOException io){io.printStackTrace();}

However the following compiles: 但是,以下编译:

try(BufferedWriter bw =Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
        {
        }
        catch(IOException io){io.printStackTrace();}

It seems that the compiler check whether or not the classes declared in the try-catch-with-resources statement implement AutoClosable ... however It could have worked since the method returns a BufferedWriter which implements AutoClosable . 似乎编译器检查在try-catch-with-resources语句中声明的类是否实现AutoClosable ... ...但是,由于该方法返回实现了AutoClosableBufferedWriter ,因此它可以工作。

Just asking for a confirmation that 只是要求确认

try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset()) 试试(Files.newBufferedWriter(Paths.get(“ / home / user / Desktop / TryItOutMan.txt”),Charset.defaultCharset())

does not compile. 无法编译。

Thanks in advance. 提前致谢。

If you look at the syntax definition of the try-with-resources in the JLS , you will see that it expects a variable name. 如果查看JLS中 try-with-resources的语法定义,您将看到它需要一个变量名。 So it must look like: 因此它必须看起来像:

try (SomeType variable = xxx;)

The Java tutorial states: Java教程指出:

The try -with-resources statement is a try statement that declares one or more resources. try -with-resources语句是一个try语句,用于声明一个或多个资源。

In your first snippet, you don't declare a resource: 在第一个代码段中,您没有声明资源:

Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt")

Whilst in your second snippet, you do: 在第二个片段中,您将执行以下操作:

BufferedWriter bw = ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM