Java字节流:FilterInputStream FilterOutputStream

-----------------------------------------------------------------------------------
  FilterInputStream、FilterOutputStream 过滤器字节输入流、输出流,这里用到了装饰器模式,它的主要用途在于给一个对象动态的添加功能。
  当我们在创建FilterInputStream、FilterOutputStream这两个类的实例时需要传入一个InputStream、OutPutStream的子类,比如:当构造FilterOutputStream时传递进去的是FileOutputStream,而FileOutputStream和FilterOutputStream实现的是同一个抽象类OutputStream,那么FilterOutputStrean对FileOutputStream的装饰对于客户端来说就是透明的,可以在FileOutputStream的方法执行之前或之后加上一些额外的操作来达到装饰的效果。
  FilterInputStream、FilterOutputStream 仅仅是对InputStream、OutputStream中所有方法进行了重写,并且只是调用传入的InputStream、OutputStream子类的方法,话句话说就是没有对传入的低级字节输入流进行任何的装饰,它们的作用是为所有字节输入流的装饰类提供一个标准、一个类似于接口的作用,具体的装饰功能由FilterInputStream、FilterOutputStream的子类来完成。
-----------------------------------------------------------------------------------
FilterInputStream
类声明:public class FilterInputStream extends InputStream
位于java.io包下
官方对其说明:
  A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. The class FilterInputStream itself simply overrides all methods of InputStream with versions that pass all requests to the contained input stream. Subclasses of FilterInputStream may further override some of these methods and may also provide additional methods and fields.
  (简单翻译:FilterInputStream包含其他一些输入流,它将这些流用作其基本数据源,它可以直接传输数据或提供一些额外的功能。FilterInputStream类本身只是简单地重写那些将所有请求传递给所包含输入流的InputStream的所有方法。FilterInputStream的子类可进一步重写这些方法中的一些方法,并且还可以提供一些额外的方法和字段。)

主要字段:
  protected InputStream in; //要过滤的输入流

构造方法:
  protected FilterInputStream(InputStream in)

主要方法:
  - int available(): 返回输入流中还可以读取的字节个数.
  - void close(): 关闭此输入流并释放与该流有关的系统资源.
  - void mark(int readlimit): 在此输入流中标记当前的位置.
  - boolean markSupported(): 检测此输入流是否支持mark和reset.
  - int read(): 从输入流中读取数据的下一个字节.
  - int read(byte[] b): 从输入流中读取一定数量的字节,并将其存储在字节数组b中
  - int read(byte[] b,int off,int len): 从输入流中读取len个字节,并将其存储在字节数组b中off位置开始的地方
  - void reset(): 将此流重新定位到最后一次对此输入流调用mark方法时的位置.
  - long skip(long n): 跳过和丢弃此输入流中n个字节的数据.

源代码如下:

  1 package java.io;
  2
  3 /**
  4  * A <code>FilterInputStream</code> contains
  5  * some other input stream, which it uses as
  6  * its  basic source of data, possibly transforming
  7  * the data along the way or providing  additional
  8  * functionality. The class <code>FilterInputStream</code>
  9  * itself simply overrides all  methods of
 10  * <code>InputStream</code> with versions that
 11  * pass all requests to the contained  input
 12  * stream. Subclasses of <code>FilterInputStream</code>
 13  * may further override some of  these methods
 14  * and may also provide additional methods
 15  * and fields.
 16  *
 17  * @author  Jonathan Payne
 18  * @since   JDK1.0
 19  */
 20 public
 21 class FilterInputStream extends InputStream {
 22     /**
 23      * The input stream to be filtered.
 24      */
 25     protected volatile InputStream in;
 26
 27     /**
 28      * Creates a <code>FilterInputStream</code>
 29      * by assigning the  argument <code>in</code>
 30      * to the field <code>this.in</code> so as
 31      * to remember it for later use.
 32      *
 33      * @param   in   the underlying input stream, or <code>null</code> if
 34      *          this instance is to be created without an underlying stream.
 35      */
 36     protected FilterInputStream(InputStream in) {
 37         this.in = in;
 38     }
 39
 40     /**
 41      * Reads the next byte of data from this input stream. The value
 42      * byte is returned as an <code>int</code> in the range
 43      * <code>0</code> to <code>255</code>. If no byte is available
 44      * because the end of the stream has been reached, the value
 45      * <code>-1</code> is returned. This method blocks until input data
 46      * is available, the end of the stream is detected, or an exception
 47      * is thrown.
 48      * <p>
 49      * This method
 50      * simply performs <code>in.read()</code> and returns the result.
 51      *
 52      * @return     the next byte of data, or <code>-1</code> if the end of the
 53      *             stream is reached.
 54      * @exception  IOException  if an I/O error occurs.
 55      * @see        java.io.FilterInputStream#in
 56      */
 57     public int read() throws IOException {
 58         return in.read();
 59     }
 60
 61     /**
 62      * Reads up to <code>byte.length</code> bytes of data from this
 63      * input stream into an array of bytes. This method blocks until some
 64      * input is available.
 65      * <p>
 66      * This method simply performs the call
 67      * <code>read(b, 0, b.length)</code> and returns
 68      * the  result. It is important that it does
 69      * <i>not</i> do <code>in.read(b)</code> instead;
 70      * certain subclasses of  <code>FilterInputStream</code>
 71      * depend on the implementation strategy actually
 72      * used.
 73      *
 74      * @param      b   the buffer into which the data is read.
 75      * @return     the total number of bytes read into the buffer, or
 76      *             <code>-1</code> if there is no more data because the end of
 77      *             the stream has been reached.
 78      * @exception  IOException  if an I/O error occurs.
 79      * @see        java.io.FilterInputStream#read(byte[], int, int)
 80      */
 81     public int read(byte b[]) throws IOException {
 82         return read(b, 0, b.length);
 83     }
 84
 85     /**
 86      * Reads up to <code>len</code> bytes of data from this input stream
 87      * into an array of bytes. If <code>len</code> is not zero, the method
 88      * blocks until some input is available; otherwise, no
 89      * bytes are read and <code>0</code> is returned.
 90      * <p>
 91      * This method simply performs <code>in.read(b, off, len)</code>
 92      * and returns the result.
 93      *
 94      * @param      b     the buffer into which the data is read.
 95      * @param      off   the start offset in the destination array <code>b</code>
 96      * @param      len   the maximum number of bytes read.
 97      * @return     the total number of bytes read into the buffer, or
 98      *             <code>-1</code> if there is no more data because the end of
 99      *             the stream has been reached.
100      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
101      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
102      * <code>len</code> is negative, or <code>len</code> is greater than
103      * <code>b.length - off</code>
104      * @exception  IOException  if an I/O error occurs.
105      * @see        java.io.FilterInputStream#in
106      */
107     public int read(byte b[], int off, int len) throws IOException {
108         return in.read(b, off, len);
109     }
110
111     /**
112      * Skips over and discards <code>n</code> bytes of data from the
113      * input stream. The <code>skip</code> method may, for a variety of
114      * reasons, end up skipping over some smaller number of bytes,
115      * possibly <code>0</code>. The actual number of bytes skipped is
116      * returned.
117      * <p>
118      * This method simply performs <code>in.skip(n)</code>.
119      *
120      * @param      n   the number of bytes to be skipped.
121      * @return     the actual number of bytes skipped.
122      * @exception  IOException  if the stream does not support seek,
123      *                          or if some other I/O error occurs.
124      */
125     public long skip(long n) throws IOException {
126         return in.skip(n);
127     }
128
129     /**
130      * Returns an estimate of the number of bytes that can be read (or
131      * skipped over) from this input stream without blocking by the next
132      * caller of a method for this input stream. The next caller might be
133      * the same thread or another thread.  A single read or skip of this
134      * many bytes will not block, but may read or skip fewer bytes.
135      * <p>
136      * This method returns the result of {@link #in in}.available().
137      *
138      * @return     an estimate of the number of bytes that can be read (or skipped
139      *             over) from this input stream without blocking.
140      * @exception  IOException  if an I/O error occurs.
141      */
142     public int available() throws IOException {
143         return in.available();
144     }
145
146     /**
147      * Closes this input stream and releases any system resources
148      * associated with the stream.
149      * This
150      * method simply performs <code>in.close()</code>.
151      *
152      * @exception  IOException  if an I/O error occurs.
153      * @see        java.io.FilterInputStream#in
154      */
155     public void close() throws IOException {
156         in.close();
157     }
158
159     /**
160      * Marks the current position in this input stream. A subsequent
161      * call to the <code>reset</code> method repositions this stream at
162      * the last marked position so that subsequent reads re-read the same bytes.
163      * <p>
164      * The <code>readlimit</code> argument tells this input stream to
165      * allow that many bytes to be read before the mark position gets
166      * invalidated.
167      * <p>
168      * This method simply performs <code>in.mark(readlimit)</code>.
169      *
170      * @param   readlimit   the maximum limit of bytes that can be read before
171      *                      the mark position becomes invalid.
172      * @see     java.io.FilterInputStream#in
173      * @see     java.io.FilterInputStream#reset()
174      */
175     public synchronized void mark(int readlimit) {
176         in.mark(readlimit);
177     }
178
179     /**
180      * Repositions this stream to the position at the time the
181      * <code>mark</code> method was last called on this input stream.
182      * <p>
183      * This method
184      * simply performs <code>in.reset()</code>.
185      * <p>
186      * Stream marks are intended to be used in
187      * situations where you need to read ahead a little to see what‘s in
188      * the stream. Often this is most easily done by invoking some
189      * general parser. If the stream is of the type handled by the
190      * parse, it just chugs along happily. If the stream is not of
191      * that type, the parser should toss an exception when it fails.
192      * If this happens within readlimit bytes, it allows the outer
193      * code to reset the stream and try another parser.
194      *
195      * @exception  IOException  if the stream has not been marked or if the
196      *               mark has been invalidated.
197      * @see        java.io.FilterInputStream#in
198      * @see        java.io.FilterInputStream#mark(int)
199      */
200     public synchronized void reset() throws IOException {
201         in.reset();
202     }
203
204     /**
205      * Tests if this input stream supports the <code>mark</code>
206      * and <code>reset</code> methods.
207      * This method
208      * simply performs <code>in.markSupported()</code>.
209      *
210      * @return  <code>true</code> if this stream type supports the
211      *          <code>mark</code> and <code>reset</code> method;
212      *          <code>false</code> otherwise.
213      * @see     java.io.FilterInputStream#in
214      * @see     java.io.InputStream#mark(int)
215      * @see     java.io.InputStream#reset()
216      */
217     public boolean markSupported() {
218         return in.markSupported();
219     }
220 }

---------------------------------------------------------------------------------------------------------------

FilterOutputStream
类声明:public class FilterOutputStream extends OutputStream
位于java.io包下
官方对其说明:
  This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.
  (简单翻译:此类是过滤输出流的所有类的超累。这些流位于已存在的输出流之上,它们将已存在的输出流作为其基本数据接收器,但可能直接传输数据或提供一些额外的功能。)
  The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream. Subclasses of FilterOutputStream may further override some of these methods as well as provide additional methods and fields.
  (简单翻译:FilterOutputStream 类本身只是简单地重写那些将所请求传递给所包含输出流的 OutputStream 的所方法。FilterOutputStream 的子类可进一步地重写这些方法中的一些方法,并且还可以提供一些额外的方法和字段。)

主要字段:
  protected OutputStream out; //要过滤的基础输出流

构造方法:
  protected FilterOutputStream(OutputStream out)

主要方法:
  - void close(): 关闭此输出流并释放与该流有关的系统资源.
  - void flush(): 刷新此输出流并强制写出所有缓冲的输出字节.
  - void write(byte[] b): 将b.length个字节从指定的byte数组写入此输出流.
  - void write(byte[] b,int off,int len): 将byte数组中从off位置开始的len个字节写入此输出流.
  - void write(int b): 将指定的字节写入此输出流.

源代码如下:

  1 package java.io;
  2
  3 /**
  4  * This class is the superclass of all classes that filter output
  5  * streams. These streams sit on top of an already existing output
  6  * stream (the <i>underlying</i> output stream) which it uses as its
  7  * basic sink of data, but possibly transforming the data along the
  8  * way or providing additional functionality.
  9  * <p>
 10  * The class <code>FilterOutputStream</code> itself simply overrides
 11  * all methods of <code>OutputStream</code> with versions that pass
 12  * all requests to the underlying output stream. Subclasses of
 13  * <code>FilterOutputStream</code> may further override some of these
 14  * methods as well as provide additional methods and fields.
 15  *
 16  * @author  Jonathan Payne
 17  * @since   JDK1.0
 18  */
 19 public
 20 class FilterOutputStream extends OutputStream {
 21     /**
 22      * The underlying output stream to be filtered.
 23      */
 24     protected OutputStream out;
 25
 26     /**
 27      * Creates an output stream filter built on top of the specified
 28      * underlying output stream.
 29      *
 30      * @param   out   the underlying output stream to be assigned to
 31      *                the field <tt>this.out</tt> for later use, or
 32      *                <code>null</code> if this instance is to be
 33      *                created without an underlying stream.
 34      */
 35     public FilterOutputStream(OutputStream out) {
 36         this.out = out;
 37     }
 38
 39     /**
 40      * Writes the specified <code>byte</code> to this output stream.
 41      * <p>
 42      * The <code>write</code> method of <code>FilterOutputStream</code>
 43      * calls the <code>write</code> method of its underlying output stream,
 44      * that is, it performs <tt>out.write(b)</tt>.
 45      * <p>
 46      * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
 47      *
 48      * @param      b   the <code>byte</code>.
 49      * @exception  IOException  if an I/O error occurs.
 50      */
 51     public void write(int b) throws IOException {
 52         out.write(b);
 53     }
 54
 55     /**
 56      * Writes <code>b.length</code> bytes to this output stream.
 57      * <p>
 58      * The <code>write</code> method of <code>FilterOutputStream</code>
 59      * calls its <code>write</code> method of three arguments with the
 60      * arguments <code>b</code>, <code>0</code>, and
 61      * <code>b.length</code>.
 62      * <p>
 63      * Note that this method does not call the one-argument
 64      * <code>write</code> method of its underlying stream with the single
 65      * argument <code>b</code>.
 66      *
 67      * @param      b   the data to be written.
 68      * @exception  IOException  if an I/O error occurs.
 69      * @see        java.io.FilterOutputStream#write(byte[], int, int)
 70      */
 71     public void write(byte b[]) throws IOException {
 72         write(b, 0, b.length);
 73     }
 74
 75     /**
 76      * Writes <code>len</code> bytes from the specified
 77      * <code>byte</code> array starting at offset <code>off</code> to
 78      * this output stream.
 79      * <p>
 80      * The <code>write</code> method of <code>FilterOutputStream</code>
 81      * calls the <code>write</code> method of one argument on each
 82      * <code>byte</code> to output.
 83      * <p>
 84      * Note that this method does not call the <code>write</code> method
 85      * of its underlying input stream with the same arguments. Subclasses
 86      * of <code>FilterOutputStream</code> should provide a more efficient
 87      * implementation of this method.
 88      *
 89      * @param      b     the data.
 90      * @param      off   the start offset in the data.
 91      * @param      len   the number of bytes to write.
 92      * @exception  IOException  if an I/O error occurs.
 93      * @see        java.io.FilterOutputStream#write(int)
 94      */
 95     public void write(byte b[], int off, int len) throws IOException {
 96         if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
 97             throw new IndexOutOfBoundsException();
 98
 99         for (int i = 0 ; i < len ; i++) {
100             write(b[off + i]);
101         }
102     }
103
104     /**
105      * Flushes this output stream and forces any buffered output bytes
106      * to be written out to the stream.
107      * <p>
108      * The <code>flush</code> method of <code>FilterOutputStream</code>
109      * calls the <code>flush</code> method of its underlying output stream.
110      *
111      * @exception  IOException  if an I/O error occurs.
112      * @see        java.io.FilterOutputStream#out
113      */
114     public void flush() throws IOException {
115         out.flush();
116     }
117
118     /**
119      * Closes this output stream and releases any system resources
120      * associated with the stream.
121      * <p>
122      * The <code>close</code> method of <code>FilterOutputStream</code>
123      * calls its <code>flush</code> method, and then calls the
124      * <code>close</code> method of its underlying output stream.
125      *
126      * @exception  IOException  if an I/O error occurs.
127      * @see        java.io.FilterOutputStream#flush()
128      * @see        java.io.FilterOutputStream#out
129      */
130     public void close() throws IOException {
131         try {
132           flush();
133         } catch (IOException ignored) {
134         }
135         out.close();
136     }
137 }

时间: 2024-10-25 18:27:56

Java字节流:FilterInputStream FilterOutputStream的相关文章

OpenJDK 源码阅读之 Java 字节流输入类的实现

Java 的输入输出总是给人一种很混乱的感觉,要想把这个问题搞清楚,必须对各种与输入输出相关的类之间的关系有所了解.只有你了解了他们之间的关系,知道设计这个类的目的是什么,才能更从容的使用他们. 我们先对 Java I/O 的总体结构进行一个总结,再通过分析源代码,给出把每个类的关键功能是如何实现的. Java I/O 的主要结构 Java 的输入输出,主要分为以下几个部分: 字节流 字符流 Socket 新 I/O 每个部分,都包含了输入和输出两部分. 实现概要 这里只给出每个类的实现概要,具

OpenJDK 源码阅读之 Java 字节流输出类的实现

Java 的输入输出总是给人一种很混乱的感觉,要想把这个问题搞清楚,必须对各种与输入输出相关的类之间的关系有所了解.只有你了解了他们之间的关系,知道设计这个类的目的是什么,才能更从容的使用他们. 这是这个系列的第二篇,描述字节输出类的实现,第一篇见:OpenJDK 源码阅读之 Java 字节流输入类的实现 字节流输出 图1 Java 字节输出类 OutputStream OutputStream是所有字节输出类的超类,这是个抽象类,需要实现其中定义的 write 函数,才能有实用的功能. pub

Java字节流操作

在java.io包中得操作主要有字节流与字符流两大类,两个类都有输入输出操作. 在字节流中,输出数据主要使用OutputStream类,输入使用的InputStream类. 在字符流中,输出数据使用Writer,输入数据使用Reader. 在Java中IO操作有相应的步骤,以文件的操作为例. (1)使用File类打开一个文件 (2)通过字节流或字符流的子类指定输出的位置. (3)进行读/写操作 (4)关闭输入/输出 字符流与字节流的区别: 字节流在操作时本身不会用到缓冲区(内存),是文件本身直接

java 字节流和字符流转换类InputStreamReader,OutPutStreamReader

import java.io.*; public class BufferDemo { public static void main(String[] args) throws IOException { BufferedReader buf=null; buf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a number:"); String str=buf

黑马程序员——关于java字节流的read()方法返回值为int的思考(转载)

------Java培训.Android培训.iOS培训..Net培训.期待与您交流! -------  之前一直不明白java字节流的read()方法返回值为什么为int,今天在网上找到了答案.以下为转载,原文地址:http://blog.sina.com.cn/s/blog_9e351f9b01015kgp.html 我们都知道java中io操作分为字节流和字符流,对于字节流,顾名思义是按字节的方式读取数据,所以我们常用字节流来读取二进制流(如图片,音乐 等文件).问题是为什么字节流中定义的

JAVA字节流(读写文件)

InputStream此抽象类是表示字节输入流的所有类的超类.需要定义 InputStream 的子类的应用程序必须始终提供返回下一个输入字节的方法. int available()返回此输入流方法的下一个调用方可以不受阻塞地从此输入流读取(或跳过)的字节数.void close()关闭此输入流并释放与该流关联的所有系统资源.void mark(int readlimit)在此输入流中标记当前的位置.boolean markSupported()测试此输入流是否支持 mark 和 reset 方

java 字节流和字符流的区别 转载

转载自:http://blog.csdn.net/cynhafa/article/details/6882061 java 字节流和字符流的区别 字节流与和字符流的使用非常相似,两者除了操作代码上的不同之外,是否还有其他的不同呢?实际上字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用了缓冲区,通过缓冲区再操作文件,如图12-6所示. 下面以两个写文件的操作为主进行比较,但是在操作时字节流和字符流的操作完成之后都不关闭输出流.范例:使用字节流不关闭执行 Java

Java字节流实现文件夹的拷贝

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** · java字节流实现文件夹的拷贝 · 拷贝文件夹,其中文件夹中又有多个文件 · 1.先遍历这个文件夹,判断是否是目录 · 2.创建文件夹 · 3.拷

Java:字节流和字符流(输入流和输出流)

本文内容: 什么是流 字节流 字符流 首发日期:2018-07-24 什么是流 流是个抽象的概念,是对输入输出设备的抽象,输入流可以看作一个输入通道,输出流可以看作一个输出通道. 输入流是相对程序而言的,外部传入数据给程序需要借助输入流. 输出流是相对程序而言的,程序把数据传输到外部需要借助输出流. 什么是字节流? 字节流--传输过程中,传输数据的最基本单位是字节的流. 什么是字符流? 字符流--传输过程中,传输数据的最基本单位是字符的流. 字符编码方式不同,有时候一个字符使用的字节数也不一样,