首页 > 编程 > Java > 正文

Java IO字节输入流常见类进行分析(二)

2019-11-08 00:46:24
字体:
来源:转载
供稿:网友

一、FileInputStream 从文件系统中读取一个文件转换成的字节 数据结构:

public class FileInputStream extends InputStream{ /* File Descriptor - handle to the open file */ PRivate final FileDescriptor fd; /* The path of the referenced file (null if the stream is created with a file descriptor) */ private final String path;//文件的路径 private FileChannel channel = null;//与文件相连的通道 private final Object closeLock = new Object(); private volatile boolean closed = false; private static final ThreadLocal<Boolean> runningFinalize = new ThreadLocal<>(); //... }

重载的构造方法

//通过文件来创建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(); } if (file.isInvalid()) { throw new FileNotFoundException("Invalid file path"); } fd = new FileDescriptor(); fd.incrementAndGetUseCount();//增加用户使用的次数 this.path = name; open(name);//打开文件 } //通过文件描述器来创建文件输入流 public FileInputStream(FileDescriptor fdObj) { SecurityManager security = System.getSecurityManager(); if (fdObj == null) { throw new NullPointerException(); } if (security != null) { security.checkRead(fdObj); } fd = fdObj; path = null; /* * FileDescriptor is being shared by streams. * Ensure that it's GC'ed only when all the streams/channels are done * using it. */ fd.incrementAndGetUseCount(); } //通过文件的路径名来创建输入流 public FileInputStream(String name) throws FileNotFoundException { this(name != null ? new File(name) : null); }

FileDescriptor是FileInputStream与文件的连接桥梁,它的创建代表着文件的打开或者socket的打开。 部分方法: close方法

public void close() throws IOException { synchronized (closeLock) {//同步锁 if (closed) { return; } closed = true; } if (channel != null) { //减少File Descriptor的数量 fd.decrementAndGetUseCount(); channel.close(); } /* *减少File Descriptor的数量 */ int useCount = fd.decrementAndGetUseCount(); /* * 如果File Descriptor的被其他流使用,那就将不会关闭 */ if ((useCount <= 0) || !isRunningFinalize()) { close0(); } }

getChannel() 增加FileDescriptor的数量

public FileChannel getChannel(){ synchronized (this) { if (channel == null) { channel = FileChannelImpl.open(fd, path, true, false, this); //增加FileDescriptor fd.incrementAndGetUseCount(); } return channel; }}

二、SocketInputStream 继承与FileInputStream,注意的是该类没有被public修饰。看一下类的结构

class SocketInputStream extends FileInputStream{ private boolean eof;//结束标志 private AbstractPlainSocketImpl impl = null;//socket现实抽象类 private byte temp[];//缓冲数据 private Socket socket = null;}

从这里可以看出,File IO和Socket IO非常的相似。 三、ObjectInputStream 一个反序列化之前写入到ObjectOutputSteam中的原生类型数据和对象类型。ObjectInputStream确保了在图中流所匹配在JVM中的java类。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表