只是确认以下内容无法编译,这不是我的错误:
try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
{
}
catch(IOException io){io.printStackTrace();}
但是以下编译:
try(BufferedWriter bw =Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
{
}
catch(IOException io){io.printStackTrace();}
编译器似乎检查了在 try-catch-with-resources 语句中声明的类是否实现了 AutoClosable
... 但是它本来可以工作,因为该方法返回一个 BufferedWriter
实现了 AutoClosable
。
只是要求确认
try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
不编译。
提前致谢。
最佳答案
如果您查看 try-with-resources in the JLS 的语法定义,您会看到它需要一个变量名。所以它必须看起来像:
try (SomeType variable = xxx;)
关于java - 关于try-with-resources语句的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053849/