Java 7 中引入的对资源 try-with-resources ,声明在 try 块中使用的资源,并保证资源将在该块执行后关闭。声明的资源需要实现自动关闭接口。
1.使用资源try
典型的try-catch-finally块:
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
try (Scanner scanner = new Scanner(new File("test.txt"))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); }
2.使用多个资源try-with-resources 块,分号分隔
try (Scanner scanner = new Scanner(new File("read.txt")); PrintWriter writer = new PrintWriter(new File("write.txt"))) { while (scanner.hasNext()) { writer.print(scanner.nextLine()); } }
3.注意:
(1)首先定义的资源会最后关闭。
(2)若要构造将由 try-with-resources 块正确处理的自定义资源,该类应实现 Closeable 或 AutoCloseable 接口并重写 close 方法。
public class MyResource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("Closed MyResource"); } }
4.Java 9 - 可以在资源try块中使用final甚至有效的final变量
final Scanner scanner = new Scanner(new File("read.txt")); PrintWriter writer = new PrintWriter(new File("write.txt")) try (scanner;writer) {
}
标签:Java,scanner,try,File,new,txt,resources,Scanner From: https://www.cnblogs.com/coder-Fish/p/17853407.html