Java Reader/Writer
In Java, Reader
and Writer
are abstract classes that provide a way to read and write characters to a stream. They are the character-based counterparts of the byte-based InputStream
and OutputStream
classes.
The Reader
class defines a set of methods that can be used to read character data from a stream, while the Writer
class defines a set of methods that can be used to write character data to a stream.
Here are some commonly used methods of the Reader
class:
read()
: This method reads a single character from the stream and returns it as an integer.read(char[] cbuf)
: This method reads characters into an array and returns the number of characters read.read(char[] cbuf, int off, int len)
: This method reads characters into a portion of an array and returns the number of characters read.skip(long n)
: This method skips over a specified number of characters in the stream.mark(int readAheadLimit)
: This method marks the current position in the stream.reset()
: This method resets the stream to the previously marked position.ready()
: This method returns true if the stream is ready to be read.close()
: This method closes the stream and releases any resources associated with it.
Here are some commonly used methods of the Writer
class:
write(int c)
: This method writes a single character to the stream.write(char[] cbuf)
: This method writes an array of characters to the stream.write(String str)
: This method writes a string to the stream.write(char[] cbuf, int off, int len)
: This method writes a portion of an array of characters to the stream.flush()
: This method flushes the stream.close()
: This method closes the stream and releases any resources associated with it.
Both Reader
and Writer
classes are used extensively for processing character-based data in Java. The classes that extend from these abstract classes include FileReader
, StringReader
, BufferedReader
, InputStreamReader
, FileWriter
, StringWriter
, and BufferedWriter
, among others.