1. FileInputStream类结构, 继承自InputStream
2. FileInputStream的方法
构造方法:
public FileInputStream(String name) throws FileNotFoundException { this (name != null ? new File(name) : null ); }
通过字符串初始化的FileInputStream最终是通过该字符串创建文件的方式初始化FileInputStream
public FileInputStream(File file) throws FileNotFoundException { String name = (file != null ? file.getPath() : null ); SecurityManager security = System.getSecurityManager(); if (security != null ) { security.checkRead(name); } if (name == null ) { throw new NullPointerException(); } fd = new FileDescriptor(); fd.incrementAndGetUseCount(); open(name); }
通过源代码我们可以看到该类用nio优化过的, 而且使用了jdk5的并发库
read()方法:
public native int read() throws IOException; private native int readBytes( byte b[], int off, int len) throws IOException;
可以看到read方法都是调用native方法, 这里就没有办法看到源代码了。和InputStream一样, 如果没有
输入可用,会一直阻塞等待
close()方法:
public void close() throws IOException { synchronized (closeLock) { if (closed) { return ; } closed = true ; } if (channel != null ) { fd.decrementAndGetUseCount(); channel.close(); } int useCount = fd.decrementAndGetUseCount(); if ((useCount <= 0 ) || ! isRunningFinalize()) { close0(); } }
关闭方法会对内部的一个对象上锁,修改是否关闭标志位,调用一系列并发方法,最终会调用一个本地的close0()方法