美文网首页
java try with resource

java try with resource

作者: 疯狂的冰块 | 来源:发表于2017-08-07 16:29 被阅读17次

你可以在块中使用多个资源而且这些资源都能被自动地关闭。下面是例子:

private static void printFileJava7() throws IOException {
   try(  FileInputStream     input         = new FileInputStream("file.txt");
         BufferedInputStream bufferedInput = new BufferedInputStream(input)
   ) {
       int data = bufferedInput.read();
       while(data != -1){
           System.out.print((char) data);
           data = bufferedInput.read();
       }
   }
}

在java 9中可更为简洁,可以将变量单独放在外边:

private static void printFileJava7() throws IOException {
    FileInputStream     input         = new FileInputStream("file.txt");
    BufferedInputStream bufferedInput = new BufferedInputStream(input)
    try(  input;bufferedInput) {
        int data = bufferedInput.read();
        while(data != -1){
            System.out.print((char) data);
            data = bufferedInput.read();
        }
    }
}

参考资料:
http://ifeve.com/java-7%E4%B8%AD%E7%9A%84try-with-resources/
在 JDK 9 中更简洁使用 try-with-resources 语句

相关文章

网友评论

      本文标题:java try with resource

      本文链接:https://www.haomeiwen.com/subject/qijalxtx.html