View RSS Feed

My Java Tips

Character Streams

Rate this Entry
by , 11-11-2011 at 06:31 PM (861 Views)
Character Streams handle I/O of character data, automatically handling translation to and from the local character set. All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. The Java platform stores character values using Unicode conventions Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization all without extra effort by the programmer.

Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter. Use them to create character streams when there are no prepackaged character stream classes that meet your needs. If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted without extensive recoding.

Example uses FileReader and FileWriter for input and output of characters. Note that use an int variable to read to and write from. After execution of program it will create file with same contents as

Java Code:

public class CopyCharactersStreams {
	public static void main(String[] args) throws IOException {
		FileReader inputStream = null;
		FileWriter outputStream = null;

		try {
			inputStream = new FileReader("");
			outputStream = new FileWriter("");

			int c;
			while ((c = != -1) {
		} finally {
			if (inputStream != null) {
			if (outputStream != null) {

Submit "Character Streams" to Facebook Submit "Character Streams" to Digg Submit "Character Streams" to Submit "Character Streams" to StumbleUpon Submit "Character Streams" to Google