关于Scanner的close的问题。

private Readable source;

if (source instanceof Closeable) {
try {
((Closeable)source).close();
} catch (IOException ioe) {
lastException = ioe;
}
}
source明明是Readable,会有可能实现Closeable吗?

虽然readable接口只有read方法,但closeable接口的close方法可以关闭此流并释放与其关联的任何系统资源。Closeable:

package java.io; import java.io.IOException; public interface Closeable { /** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. */ public void close() throws IOException; }
Readable:

package java.lang; import java.io.IOException; public interface Readable { /** * Attempts to read characters into the specified character buffer. * The buffer is used as a repository of characters as-is: the only * changes made are the results of a put operation. No flipping or * rewinding of the buffer is performed. */ public int read(java.nio.CharBuffer cb) throws IOException; }

source明明是Readable,会有可能实现Closeable吗?

会啊,而且很多都是,看下java.io.Reader及其子类

可以实现,(XXX.close)

原因是我再初始化时,实例化了一个InputStreamReader,这个类继承了Readable,所以这个source instanceof Closeable没问题,然后关闭流。