Thetry-with-resourcesstatement doesautomatic resource management. We need not explicitly close the resources as JVM automatically closes them. This makes the code more readable and easier to write. 2. try-with-resources with multiple resources We can declare more than one resource in thetry-with-...
// try-finally is ugly when used with more than one resource!staticvoidcopy(String src, String dst)throwsIOException {InputStreamin=newFileInputStream(src);try{OutputStreamout=newFileOutputStream(dst);try{byte[] buf =newbyte[BUFFER_SIZE];intn;while((n = in.read(buf)) >=0) out.write(...
可以看到,编译器使用传统的try-finally 写法贴心的为我们添加了资源关闭的代码,而且资源关闭的顺序是:try 括号内先声明的资源后关闭,后声明的资源先关闭。而且关闭资源时,若发生异常,其会将其压制,而抛出 try-with-resources 块内发生的异常。4 Java 7:try-with-resources 自动资源关闭具备的优点...
// src/test/java/TryWithResourcesTest#testJava7ReadFileWithMultipleResources @Test public void testJava7ReadFileWithMultipleResources() throws IOException { String filePath = this.getClass().getResource("test.txt").getPath(); try (FileReader fr = new FileReader(filePath); BufferedReader br = ...
This may not look bad, but it gets worse when you add a second resource: 这可能看起来不坏,但添加第二个资源时,情况会变得更糟: // try-finally is ugly when used with more than one resource!staticvoidcopy(Stringsrc,Stringdst)throws IOException{InputStreamin=newFileInputStream(src);try{Output...
// src/test/java/TryWithResourcesTest#testJava7ReadFileWithMultipleResources @Test publicvoidtestJava7ReadFileWithMultipleResources()throwsIOException{ String filePath =this.getClass().getResource("test.txt").getPath(); try(FileReader fr =newFileReader(filePath); ...
1.All the classes cannot be used in try-with-resources. AutoCloseable is an interface used as a contract to implement try-with-resources. Classes that implements AutoCloseable must be used as a resource in try-with-resources, else we will get compilation error. ...
So this way, we don’t even need to write finally block to close the resource.Even if we forget to close resources, Java takes care of it.We can also use multiple resources within try as belowprivate static void readFileJava7() throws IOException { try( FileInputStream input = new ...
// close your resource in the appropriate way } } 异常处理 如果从Javatry-with-resources块中引发异常,则在该块的括号内打开的任何资源try仍将自动关闭。 如前所述,try-with-resources的工作原理与try-catch-finally相同,只是增加了一点点。这种增加称为抑制异常。这是不是有必要了解为了使用抑制异常的try-与...
// 当打开超过1个资源, try-finally 可能用起来就比较难受了//try-finally is ugly when used with more than one resource!static voidcopy(String src,String dst)throws IOException{int BUFFER_SIZE=2048;InputStreamin=newFileInputStream(src);try{OutputStream out=newFileOutputStream(dst);try{byte[]buf...