Java Reference
In-Depth Information
ultsinacalltooneoftheunderlyingplatform'snativemethods,andthesenativemethod
calls slow down I/O. (I discuss native methods in Appendix C.)
The concrete
BufferedOutputStream
and
BufferedInputStream
filter
streamclassesimproveperformancebyminimizingunderlyingoutputstream
write()
andunderlyinginputstream
read()
methodcalls.Instead,callsto
BufferedOut-
putStream
's
write()
and
BufferedInputStream
's
read()
methods take
Java buffers into account:
• When a write buffer is full,
write()
calls the underlying output stream
write()
method to empty the buffer. Subsequent calls to
BufferedOut-
putStream
's
write()
methods store bytes in this buffer until it's once
again full.
• When the read buffer is empty,
read()
calls the underlying input stream
read()
method to fill the buffer. Subsequent calls to
BufferedIn-
putStream
's
read()
methods return bytes from this buffer until it's once
again empty.
BufferedOutputStream
declares the following constructors:
•
BufferedOutputStream(OutputStream out)
createsabufferedout-
putstreamthatstreamsitsoutputto
out
.Aninternalbufferiscreatedtostore
bytes written to
out
.
•
BufferedOutputStream(OutputStream out, int size)
creates
a buffered output stream that streams its output to
out
. An internal buffer of
length
size
is created to store bytes written to
out
.
The following example chains a
BufferedOutputStream
instance to a
FileOutputStream
instance. Subsequent
write()
method calls on the
BufferedOutputStream
instance buffer bytes and occasionally result in internal
write()
method calls on the encapsulated
FileOutputStream
instance:
FileOutputStream
fos
=
new
FileOut-
putStream("employee.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
// Chain bos to fos.
bos.write(0); // Write to employee.dat through the buffer.
// Additional write() method calls.
bos.close(); // This method call internally calls fos's
close() method.
BufferedInputStream
declares the following constructors: