Java关闭BufferedReader,Scanner和FileReader

时间:2012-12-23 10:52:50

标签: java java.util.scanner bufferedreader

在我的程序中,我解析文件。我这样打开它们:

Scanner s = new Scanner(new BufferedReader(new FileReader("file1.txt")));

然后关闭它:

s.close();

我的问题是:当我做s.close()时,这也会关闭FileReader和BufferedReader吗?

1 个答案:

答案 0 :(得分:2)

Java doc说

public void close()

Closes this scanner.

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

Attempting to perform search operations after a scanner has been closed will result in an IllegalStateException. 

由于BufferedReader已实现Closeable,因此它将调用缓冲区读取器关闭方法。