Just the way binary streams operate on binary files, the character streams operate on character files—that is, text files such as .txt, .odt, and .docx. Just the way we have several real (fully implemented) subclasses of input and output byte stream types, we have several real classes of input and output character stream types. The high-level class hierarchy for character stream classes is given here
The Reader and Writer classes act as super classes for the rest of the classes in this category. Several Reader/Writer subclasses are available that match the corresponding byte stream classes in functionality, except they work on character streams rather than byte streams.
Java provides the BufferedReader and BufferedWriter classes, which provide the in-built buffers. Remember that reading a single byte or 512 bytes at a time requires the same amount of I/O processing. Therefore, buffering characters makes file reading and writing more efficient.
When we use these classes, we may specify the size for the buffer; otherwise, a default size is used that is adequate for most purposes. If we have a lot of system memory, we may allocate a larger buffer to provide data caching so as to avoid frequent reads and writes from and to a physical disk.
The BufferedReader Class
Typically, we would construct an instance of the BufferedReader class as follows:
BufferedReader reader = new BufferedReader(new FileReader("filename"));
- We first construct an instance of the FileReader class by specifying the name of the file to be opened in its parameterized constructor.
- We use this instance of the FileReader class as a parameter to BufferedReader during its instantiation.
- Once the reader object is constructed, we may call its various overloaded read methods to read the file contents. A typical method for reading the file line by line is the readLine method:
public String readLine() throws IOException
- The readLine method reads one line at a time from the input stream and returns it to the caller as a String object.
- A line is terminated by either a linefeed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
- The returned string does not include the line-termination character. It returns null on reaching the end of the stream.
The BufferedWriter Class
Similar to the BufferedReader class, Java provides a BufferedWriter class for efficient writing to the files. We construct an instance of BufferedWriter as follows:
BufferedWriter writer = new BufferedWriter(new FileWriter("mindstick.out"));
- This creates a file called mindstick.out if it does not already exist; if the file exists, its contents will be overwritten.
- After the file is opened for writing, the BufferedWriter creates a wrapper on it to provide efficient write operations that can accept the data to be written in a character array format or a string.
- It also provides a newline method that writes a newline character to the output stream.