简体   繁体   English

如果我关闭 Scanner,我是否必须关闭 FileInputStream

[英]Do I have to close FileInputStream if I close Scanner

I have read this question: Do I have to close FileInputStream?我读过这个问题:我必须关闭 FileInputStream 吗?

What if I use a Scanner like this https://www.baeldung.com/java-scanner and close the Scanner?如果我使用像https://www.baeldung.com/java-scanner这样的扫描仪并关闭扫描仪会怎样? Does the scanner.close() close the FileInputStream as well? scanner.close()是否也关闭了 FileInputStream?

Yes it will.是的,它会的。 Consider the following code:考虑以下代码:

FileInputStream inputStream = new FileInputStream("file.txt");
Scanner scanner = new Scanner(inputStream);
scanner.close();
System.out.println(inputStream.read());

This throws a java.io.IOException because the stream is closed.这会引发java.io.IOException ,因为 stream 已关闭。

Edit: Or, as said by Slaw , check the documentation .编辑:或者,正如Slaw 所说,检查文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM