Reading and Writing data in text formats

There are two different ways to store data. Text and Binary Format. In this article we will cover only text format. We will discuss binary format in our next article.

  • Text Format
    • In text format, data is represented in human read able format
    • Reader and Writer classes or their subclasses handle data in text form
    • It is easier to produce output e.g. just use text editor
    • It is easier to check that output is correct in output file

Reader class and subclasses hierarchy

  • InputStreamReader
    • FileReader

Class Reader

Modifier Type Constructors / Methods Description
protected Reader() Creates a new character-stream reader whose critical sections will synchronize on the reader itself
protected Reader(Object lock) Creates a new character-stream reader whose critical sections will synchronize on the given object
abstract void close() Closes the stream and releases any system resources associated with it
void mark(int readAheadLimit) Marks the present position in the stream
boolean markSupported() Tells whether this stream supports the mark() operation
int read() Reads a single character
int read(char[] cbuf) Reads characters into an array
abstract int read(char[] cbuf, int off, int len) Reads characters into a portion of an array
int read(CharBuffer target) Attempts to read characters into the specified character buffer
boolean ready() Tells whether this stream is ready to be read
void reset() Resets the stream
long skip(long n) Skips characters

Class InputStreamReader

Modifier Type Constructors / Methods Description
InputStreamReader(InputStream in) Creates an InputStreamReader that uses the default charset
InputStreamReader(InputStream in, Charset cs) Creates an InputStreamReader that uses the given charset
InputStreamReader(InputStream in, CharsetDecoder dec) Creates an InputStreamReader that uses the given charset decoder
InputStreamReader(InputStream in, String charsetName) Creates an InputStreamReader that uses the named charset
void close() Closes the stream and releases any system resources associated with it
String getEncoding() Returns the name of the character encoding being used by this stream
int read() Reads a single character
int read(char[] cbuf, int offset, int length) Reads characters into a portion of an array
boolean ready() Tells whether this stream is ready to be read

Class FileReader

Modifier Type Constructors / Methods Description
FileReader(File file) Creates a new FileReader, given the File to read from
FileReader(FileDescriptor fd) Creates a new FileReader, given the FileDescriptor to read from.
FileReader(String fileName) Creates a new FileReader, given the name of the file to read from

Writer class and subclasses hierarchy

  • OutPutStreamWriter
    • FileWriter
  • PrintWriter

Class Writer

Modifier Type Constructors / Methods Description
protected Writer() Creates a new character-stream writer whose critical sections will synchronize on the writer itself
protected Writer(Object lock) Creates a new character-stream writer whose critical sections will synchronize on the given object
Writer append(char c) Appends the specified character to this writer
Writer append(CharSequence csq) Appends the specified character sequence to this writer
Writer append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to this writer
abstract void close() Closes the stream, flushing it first
abstract void flush() Flushes the stream.
void write(char[] cbuf) Writes an array of characters
abstract void write(char[] cbuf, int off, int len) Writes a portion of an array of characters
void write(int c) Writes a single character
void write(String str) Writes a string
void write(String str, int off, int len) Writes a portion of a string

Class OutputStreamWriter

Modifier Type Constructors / Methods Description
OutputStreamWriter(OutputStream out) Creates an OutputStreamWriter that uses the default character encoding
OutputStreamWriter(OutputStream out, Charset cs) Creates an OutputStreamWriter that uses the given charset
OutputStreamWriter(OutputStream out, CharsetEncoder enc) Creates an OutputStreamWriter that uses the given charset encoder
OutputStreamWriter(OutputStream out, String charsetName) Creates an OutputStreamWriter that uses the named charset
void close() Closes the stream, flushing it first
void flush() Flushes the stream
String getEncoding() Returns the name of the character encoding being used by this stream.
void write(char[] cbuf, int off, int len) Writes a portion of an array of characters
void write(int c) Writes a single character
void write(String str, int off, int len) Writes a portion of a string

Class FileWriter

Modifier Type Constructors / Methods Description
FileWriter(File file) Constructs a FileWriter object given a File object
FileWriter(File file, boolean append) Constructs a FileWriter object given a File object
FileWriter(FileDescriptor fd) Constructs a FileWriter object associated with a file descriptor.
FileWriter(String fileName) Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append) Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written

Example Program : How to read and write text

We can read text from a file using FileReader class whereas we can write text in a file using FileWriter class. Example given below implements methods to read and write text in a file. Have a look at program given below.

package javabasic;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 
 * @author Gulraiz
 *
 */
public class FileHandler {
	/**
	 * @throws IOException
	 */
	public static void readFile() throws IOException {
		FileReader file = new FileReader("test.txt");
		BufferedReader reader = new BufferedReader(file);
		String str;
		while ((str = reader.readLine()) != null)
			System.out.println(str);

	}

	public static void writeFile() throws IOException {
		FileWriter writer = new FileWriter("write.text");
		String str = "Hello and Welcome to file writer tutorial!!";
		writer.write(str);
		writer.close();
	}

	public static void main(String args[]) {
		try {
			readFile();
			writeFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


Note : Text input and output are very convenient for human, because it is much easier to produce input and validate output. But machine is not very efficient while storing, reading and writing text format.

For more details watch video tutorial