java i/o库关键知识

来源:互联网 发布:阿里云服务器内网互通 编辑:程序博客网 时间:2024/05/24 20:06
知识点一: 四大等级结构
java语言的i/o库提供了四大等级结构:InputStream,OutputStream,Reader,Writer四个系列的类。InputStream和OutputStream处理8位字节流数据, Reader和Writer处理16位的字符流数据。InputStream和Reader处理输入, OutputStream和Writer处理输出。大家一定要到J2SE文档中看看这四大等级结构的类继承体系。
除了这四大系列类,i/o库还提供了少数的辅助类,其中比较重要的是InputStreamReader和OutputStreamWriter。InputStreamReader把InputStream适配为Reader, OutputStreamWriter把OutputStream适配为Writer;这样就架起了字节流处理类和字符流处理类间的桥梁。
您使用i/o库时,只要按以上的规则,到相应的类体系中寻找您需要的类即可。
知识点二: 适配功能
java i/o库中的继承不是普通的继承;它的继承模式分为两种,其一就是Adapter模式(具体分析请参见<>一书) 。下面以InputStream类体系为例进行说明。
InputStream有7个直接子类:ByteArrayInputStream,FileInputStream,PipedInputStream,StringBufferInputStream,FilterInputStream,ObjectInputStream和SequenceInputStream。前四个采用了Adapter模式,如FileInputStream部分代码如下:
Public class FileInputStream extends InputStream
{
 /* File Descriptor - handle to the open file */
 private FileDescriptor fd;
 public FileInputStream(FileDescriptor fdObj)
{
SecurityManager security = System.getSecurityManager();
 if (fdObj == null) {
 throw new NullPointerException();
}
 if (security != null) {
 security.checkRead(fdObj);
}
fd = fdObj;
}
//其他代码
}
可见,FileInputStream继承了InputStream,组合了FileDescriptor,采用的是对象Adapter模式。我们学习i/o库时,主要应该掌握这四个对象Adapter模式的适配源: ByteArrayInputStream的适配源是Byte数组, FileInputStream的适配源是File对象, PipedInputStream的适配源是PipedOutputStream对象, StringBufferInputStream的适配源是String对象。其它三个系列类的学习方法与此相同。
知识点三: Decorator功能
InputStream的其它三个直接子类采用的是Decorator模式,<>中描述得比较清楚,其实我们不用管它采用什么模式,看看代码就明白了。 FilterInputStream部分代码如下:
Public class FilterInputStream extends InputStream {
/**
* The input stream to be filtered. 
 */
protected InputStream in;
 protected FilterInputStream(InputStream in) {
 this.in = in;
}
 //其它代码
}
?看清楚没有? FilterInputStream继承了InputStream,也引用了InputStream,而它有四个子类,这就是所谓的Decorator模式。我们暂时可以不管为什么要用Decorator模式,但我们现在应该知道:因为InputStream还有其它的几个子类,所以我们可以将其它子类作为参数来构造FilterInputStream对象!这是我们开发时常用的功能,代码示例如下: {
//从密钥文件中读密钥
SecretKey key=null;?? 
ObjectInputStream keyFile=new ObjectInputStream(
 new FileInputStream("c://安全文件//对称密钥//yhb.des"));
key=(SecretKey)keyFile.readObject();
keyFile.close();
}
上面的代码中, ObjectInputStream也是InputStream的子类,也使用了Decorator功能,不过,就算你不懂也不想懂Decorator模式,只要记住本文给出的FilterInputStream 的两段代码即可。
掌握了以上三点,相信我们已经能够很好的应用java i/o库。
 
原创粉丝点击