说说Java7 之 Try with Resources

義往昔 1月前 ⋅ 31 阅读

https://blog.csdn.net/neweastsun/article/details/82055743

java7引入Try with Resources语法,允许我们在try块中声明并使用资源,确保在使用之后资源被关闭。资源必须实现AuthCloseable接口。

使用Try with Resources

简单地说,为了自动关闭,资源必须在try块中声明并初始化,示例如下:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

eg:

Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

 

try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

 

多个资源
try (Scanner scanner = new Scanner(new File("testRead.txt"));
    PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
    while (scanner.hasNext()) {
    writer.print(scanner.nextLine());
    }
}

https://blog.csdn.net/neweastsun/article/details/82055743

 


注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: