我正试图了解尝试使用资源。阅读了几篇文章后,我了解到实现或扩展可关闭/自动关闭的每个类都可以从close()
方法中受益,该方法被称为关闭对象。
现在在实践中我有以下代码:
try (FileInputStream inputStream = new FileInputStream(instructionFile);
Scanner sc = new Scanner(inputStream, "UTF-8")) {
while (sc.hasNextLine()) {
String startingPosition = sc.nextLine();
String instructions = sc.nextLine();
// Some actions
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} catch (NoSuchElementException e) {
throw new IncompleteInstructions();
} catch (IOException e) {
throw e;
}
如您所见,我使用了FileInputStream
和Scanner
类,我希望看到这两个类的实现或扩展Closable
,而我有经典的方法{{1 }},似乎是close()
的包装。
我的问题是谁应该实现或扩展Closable
,它是数据源,例如Closable
类的文件和FileInputStream
类的Readable接口。
谢谢!
答案 0 :(得分:3)
您的两个类都实现了Closeable
,该类扩展了AutoCloseable
。
读取Javadoc会有所帮助,但是最后,try-with-resources将自动调用其close
方法。
在关闭之前可以保存资源(例如文件或套接字句柄)的对象。退出
close()
-with-resources块时,将自动调用AutoCloseable
对象的try
方法,该对象已在资源规范头中声明了该对象。这种结构可确保及时释放,避免资源耗尽异常和可能发生的错误。
答案 1 :(得分:0)
FileInputStream
扩展了InputeStream
InputStream
和Scanner
都实现Closable
Closable
扩展了AutoClosable
因此FileInputStream
和Scanner
实例为AutoClosable
,并且在try块中的指令完成执行之后,JVM将自动在这些资源上调用.close()
方法。在Java docs状态下,
try-with-resources语句可确保关闭每个资源 在声明的末尾。