原文地址:http://blog.csdn.net/qq924862077/article/details/52728835
FilterInputStream的作用是用来封装其他的输入流,并为它们提供了额外的功能,它的常用的子类有BufferedInputStream和DataInputStream。FilterOutputStream的作用是用来封装其他的输出流,并为它们提供额外的功能,主要包括BufferedOutputStream,DataOutputStream和PrintStream。
基于JDK8的FilterInputStream的源码:
- public class FilterInputStream extends InputStream {
- /**
- * The input stream to be filtered.
- */
- //InputStream
- protected volatile InputStream in;
- /**
- * Creates a <code>FilterInputStream</code>
- * by assigning the argument <code>in</code>
- * to the field <code>this.in</code> so as
- * to remember it for later use.
- *
- * @param in the underlying input stream, or <code>null</code> if
- * this instance is to be created without an underlying stream.
- */
- protected FilterInputStream(InputStream in) {
- this.in = in;
- }
- //从输入流读取下一个字节
- public int read() throws IOException {
- return in.read();
- }
- //从输入流中读取len长度的字节
- public int read(byte b[]) throws IOException {
- return read(b, 0, b.length);
- }
- public int read(byte b[], int off, int len) throws IOException {
- return in.read(b, off, len);
- }
- //跳过长度
- public long skip(long n) throws IOException {
- return in.skip(n);
- }
- //是否还有数据
- public int available() throws IOException {
- return in.available();
- }
- //关闭资源
- public void close() throws IOException {
- in.close();
- }
- //标记在输入流的当前位置
- public synchronized void mark(int readlimit) {
- in.mark(readlimit);
- }
- //重置上次位置
- public synchronized void reset() throws IOException {
- in.reset();
- }
- //判断是否支持重置和标记
- public boolean markSupported() {
- return in.markSupported();
- }
- }
基于JDK8的FilterOutputStream源码:
- public class FilterOutputStream extends OutputStream {
- /**
- * The underlying output stream to be filtered.
- */
- protected OutputStream out;
- public FilterOutputStream(OutputStream out) {
- this.out = out;
- }
- //写到输入流中
- public void write(int b) throws IOException {
- out.write(b);
- }
- //写b到输入流中
- public void write(byte b[]) throws IOException {
- write(b, 0, b.length);
- }
- //写b中的起始位置为off,长度为len
- public void write(byte b[], int off, int len) throws IOException {
- if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
- throw new IndexOutOfBoundsException();
- for (int i = 0 ; i < len ; i++) {
- write(b[off + i]);
- }
- }
- /**
- * Flushes this output stream and forces any buffered output bytes
- * to be written out to the stream.
- * <p>
- * The <code>flush</code> method of <code>FilterOutputStream</code>
- * calls the <code>flush</code> method of its underlying output stream.
- *
- * @exception IOException if an I/O error occurs.
- * @see java.io.FilterOutputStream#out
- */
- //刷新,强制所有的缓冲数据都被写出
- public void flush() throws IOException {
- out.flush();
- }
- //关闭资源
- @SuppressWarnings("try")
- public void close() throws IOException {
- try (OutputStream ostream = out) {
- flush();
- }
- }
- }