转载:https://blog.csdn.net/fanxiaobin577328725/article/details/53067163
首先看代码:
import org.junit.Test; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class TryWithResources { @Test public void test() throws FileNotFoundException { FileInputStream inputStream1 = new FileInputStream("e:\\ipscan.txt"); InputStreamReader reader1 = new InputStreamReader(inputStream1); BufferedReader br1 = new BufferedReader(reader1); FileInputStream inputStream2 = new FileInputStream("g:\\sample.txt"); InputStreamReader reader2 = new InputStreamReader(inputStream2); BufferedReader br2 = new BufferedReader(reader2); try(BufferedReader b3 = new BufferedReader(reader2);BufferedReader b4 = new BufferedReader(reader1)) { System.out.println(br1.readLine()+br2.readLine()); }catch (Exception e) { System.err.println(e); } //JAVA9才支持 // try(br1;br2) // { // System.out.println(br1.readLine()+br2.readLine()); // }catch (Exception e) // { // System.err.println(e); // } } }
使用前置条件:实现java.lang.AutoCloseable接口
java1.7引入的新特性。类似于C#的using语句块,只要类实现了IDisposable接口
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。