Java中FilterInputStream和FilterOutputStream的用法详解
FilterInputStream
FilterInputStream的作用是用来“封装其它的输入流,并为它们提供额外的功能”。它的常用的子类有BufferedInputStream和DataInputStream。
BufferedInputStream的作用就是为“输入流提供缓冲功能,以及mark()和reset()功能”。
DataInputStream是用来装饰其它输入流,它“允许应用程序以与机器无关方式从底层输入流中读取基本Java数据类型”。应用程序可以使用DataOutputStream(数据输出流)写入由DataInputStream(数据输入流)读取的数据。
FilterInputStream源码(基于jdk1.7.40):
packagejava.io;
publicclassFilterInputStreamextendsInputStream{
protectedvolatileInputStreamin;
protectedFilterInputStream(InputStreamin){
this.in=in;
}
publicintread()throwsIOException{
returnin.read();
}
publicintread(byteb[])throwsIOException{
returnread(b,0,b.length);
}
publicintread(byteb[],intoff,intlen)throwsIOException{
returnin.read(b,off,len);
}
publiclongskip(longn)throwsIOException{
returnin.skip(n);
}
publicintavailable()throwsIOException{
returnin.available();
}
publicvoidclose()throwsIOException{
in.close();
}
publicsynchronizedvoidmark(intreadlimit){
in.mark(readlimit);
}
publicsynchronizedvoidreset()throwsIOException{
in.reset();
}
publicbooleanmarkSupported(){
returnin.markSupported();
}
}
FilterOutputStream
FilterOutputStream的作用是用来“封装其它的输出流,并为它们提供额外的功能”。它主要包括BufferedOutputStream,DataOutputStream和PrintStream。
(01)BufferedOutputStream的作用就是为“输出流提供缓冲功能”。
(02)DataOutputStream是用来装饰其它输出流,将DataOutputStream和DataInputStream输入流配合使用,“允许应用程序以与机器无关方式从底层输入流中读写基本Java数据类型”。
(03)PrintStream是用来装饰其它输出流。它能为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。
FilterOutputStream源码(基于jdk1.7.40):
packagejava.io;
publicclassFilterOutputStreamextendsOutputStream{
protectedOutputStreamout;
publicFilterOutputStream(OutputStreamout){
this.out=out;
}
publicvoidwrite(intb)throwsIOException{
out.write(b);
}
publicvoidwrite(byteb[])throwsIOException{
write(b,0,b.length);
}
publicvoidwrite(byteb[],intoff,intlen)throwsIOException{
if((off|len|(b.length-(len+off))|(off+len))<0)
thrownewIndexOutOfBoundsException();
for(inti=0;i<len;i++){
write(b[off+i]);
}
}
publicvoidflush()throwsIOException{
out.flush();
}
publicvoidclose()throwsIOException{
try{
flush();
}catch(IOExceptionignored){
}
out.close();
}
}