Reading Bytes – classes
The basic class in java.io to read data is java.io.InputStream. All classes that read bytes are derived from this class. This class is extended by the following classes. Detailed examples follow later, but lets take a 10000 feet view of the classes. We will look only at the most important classes.
- FileInputStream- This stream reads raw bytes from a file. The read methods in this class return a byte of data read from a file.
- ObjectInputStream- This class is used to read objects written using ObjectOutputStream. It deserializes the primitive data types and objects
- PipedInputStream- A unix ‘pipe’ like implementation can be accomplished using this class. It can connect to a pipedoutputsteam and read data off it.
- BufferedInputStream- This is probably the most used class. It buffers the data from any of the above inputstream. The methods in this class increase reading efficiency since they try to read the maximum number of bytes that can be read from the file system in one operation.
- ByteArrayInputStream-This class contains a buffer(array) or bytes that store the next few bytes that will be read from the stream.
Writing Bytes – classes
All classes that write bytes extend java.io.OutputStream. The important classes are:
- FileOutputStream- The methods in this class write bytes of data to a file. Note that this writes raw bytes and not characters.
- ObjectOutputStream – writes primitive java types and objects to an ouputstream. The data could be written to a file or to a socket. Data written using this method can be read back using the ObjectInputStream
- PipedOutputStream- A piped output stream connects to a PipedInputStream to read bytes. Data may be written by one thread and read by another.
- BufferedOutputStream-It buffers data from an inputstream and writes the buffered data. It is an efficient method of writing data since the operating systems may write an array of bytes in a single operation and invoking write operation for each byte may be inefficient
- PrintStream-It wraps an InputStream and adds functionality to print various representations of data values. It never throws IOException and there is an option for automatic flushing
- ByteArrayOutputStream-This class writes bytes at an array of bytes.
Example- Read and write without buffering
Read bytes from a file and write to another file.
Example- Read and write with buffering
use a Buffer to read and write bytes