java的基本输入流是java.io.InputStream,该抽象类定义了输入流的基本输入操作方法,实现自该抽象类的子类都有定义自己的数据源,例如ByteArrayInputStream的构造函数指定了ByteArrayInputStream输入流的数据源必须是一个字符数组。这就可以有多种不同的数据源,包括:字符数组、String对象、文件、“管道”、一个由其他种类的流组成的序列...

1 public ByteArrayInputStream(byte buf[]) {}
2 
3 public ByteArrayInputStream(byte buf[], int offset, int length) {}

 InputStream子类的继承结构如下,这里列举部分子类,还有很多未能列举:

java IO之输入流——InputStream

下面对这些不同的输入流稍加分析

1、ByteArrayInputStream,它包含一个内部缓冲区,该缓冲区包含从流中读取的字节。内部计数器跟踪 read 方法要提供的下一个字节。 下面是它的源码:

 1 public class ByteArrayInputStream extends InputStream {
 2     protected byte buf[];
 3     protected int pos;
 4     protected int mark = 0;
 5     protected int count;
 6     public ByteArrayInputStream(byte buf[]) {
 7         this.buf = buf;
 8         this.pos = 0;
 9         this.count = buf.length;
10     }
11     public ByteArrayInputStream(byte buf[], int offset, int length) {
12         this.buf = buf;
13         this.pos = offset;
14         this.count = Math.min(offset + length, buf.length);
15         this.mark = offset;
16     }
17     public synchronized int read() {
18         return (pos < count) ? (buf[pos++] & 0xff) : -1;
19     }
20     public synchronized int read(byte b[], int off, int len) {
21         if (b == null) {
22             throw new NullPointerException();
23         } else if (off < 0 || len < 0 || len > b.length - off) {
24             throw new IndexOutOfBoundsException();
25         }
26 
27         if (pos >= count) {
28             return -1;
29         }
30 
31         int avail = count - pos;
32         if (len > avail) {
33             len = avail;
34         }
35         if (len <= 0) {
36             return 0;
37         }
38         System.arraycopy(buf, pos, b, off, len);
39         pos += len;
40         return len;
41     }
42     public synchronized long skip(long n) {
43         long k = count - pos;
44         if (n < k) {
45             k = n < 0 ? 0 : n;
46         }
47         pos += k;
48         return k;
49     }
50     public synchronized int available() {
51         return count - pos;
52     }
53     public boolean markSupported() {
54         return true;
55     }
56     public void mark(int readAheadLimit) {
57         mark = pos;
58     }
59     public synchronized void reset() {
60         pos = mark;
61     }
62     public void close() throws IOException {
63     }
64 }
View Code

相关文章: