Defined
Inherits the InputStream, the data source is the built-in byte array buf, the mission of the Read () method (reads one byte out), in Bytearrayinputstream is simply through the directed take BUF element realization
Core Source Understanding
Source:
1 Public Bytearrayinputstream (byteintint length) {2this . buf = buf; 3 this. pos = offset; 4 this. Count = Math.min (offset + length, buf.length); 5 this. Mark = offset; 6 }
Understand:
1. Constructs the Bytearrayinputstream, directly the external byte array as the built-in buf, as the data source to be read
Source:
1 //where the data is stored2 protected bytebuf[];3 4 //The next location to be read, which is the location to wait for the read5 protected intPos;6 7 //mark the location of POS8 protected intMark = 0;9 Ten //the number of bytes actually capable of being read One protected intCount
Understand:
Source:
1 public synchronized int Read () { 2 return (pos < count)? (buf[pos++] & 0xff):-1;}
Understand:
1. This method is synchronized modified, other methods are also, so bytearrayinputstream is thread-safe
2. Byte type and 0xFF do and operation, turn to the unsigned type of byte (0-255), the previous section also illustrates
Source:
1 Public synchronized intReadbyteB[],intOffintLen) {2 if(b = =NULL) {3 Throw Newnullpointerexception ();4}Else if(Off < 0 | | Len < 0 | | len > B.length-off) {5 Throw Newindexoutofboundsexception ();6 }7 8 if(Pos >=count) {9 return-1;Ten } One A intAvail = count-Pos; - if(Len >avail) { -Len =avail; the } - if(Len <= 0) { - return0; - } + system.arraycopy (buf, POS, B, off, Len); -pos + =Len; + returnLen; A}
Understand:
1. Because the data source is a byte array, the destination source is also a byte array, so directly using the array copy method, written to the B array
Source:
1 Public synchronized LongSkipLongN) {2 LongK = Count-Pos;3 if(N <k) {4k = N < 0? 0: N;5 }6 7pos + =K;8 returnK;9}
Understand:
1. To implement the skip operation by adjusting the value of the POS
Summarize:
1. The mark and reset methods are implemented, and the Mark method makes Mark=pos,reset Pos=mark easier to understand.
Problem:
No
Reference:
Java I/O series (ii) Bytearrayinputstream source code Analysis and understanding