public class RandomAccessFile implements DataOutput, DataInput { public final byte readByte() throws IOException { int ch = this.read(); if (ch < 0) throw new EOFException(); return (byte)(ch); }
public native int read() throws IOException;
public final void writeByte(int v) throws IOException { write(v); }
public native void write(int b) throws IOException; }
可见,RandomAccessFile每读/写一个字节就需对磁盘进行一次I/O操作。
1.2.[BufferedInputStream]
public class BufferedInputStream extends FilterInputStream { PRivate static int defaultBufferSize = 2048; protected byte buf[]; // 建立读缓存区 public BufferedInputStream(InputStream in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } public synchronized int read() throws IOException { ensureOpen(); if (pos >= count) { fill(); if (pos >= count) return -1; } return buf[pos++] & 0xff; // 直接从BUF[]中读取 } private void fill() throws IOException { if (markpos < 0) pos = 0; /* no mark: throw away the buffer */ else if (pos >= buf.length) /* no room left in buffer */ if (markpos > 0) { /* can throw away early part of the buffer */ int sz = pos - markpos; System.arraycopy(buf, markpos, buf, 0, sz); pos = sz; markpos = 0; } else if (buf.length >= marklimit) { markpos = -1; /* buffer got too big, invalidate mark */ pos = 0; /* drop buffer contents */ } else { /* grow buffer */ int nsz = pos * 2; if (nsz > marklimit) nsz = marklimit; byte nbuf[] = new byte[nsz]; System.arraycopy(buf, 0, nbuf, 0, pos); buf = nbuf; } count = pos; int n = in.read(buf, pos, buf.length - pos); if (n > 0) count = n + pos; } }
1.3.[BufferedOutputStream]
public class BufferedOutputStream extends FilterOutputStream { protected byte buf[]; // 建立写缓存区 public BufferedOutputStream(OutputStream out, int size) { super(out); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } public synchronized void write(int b) throws IOException { if (count >= buf.length) { flushBuffer(); } buf[count++] = (byte)b; // 直接从BUF[]中读取 }