View RSS Feed

My Java Tips

Character Streams

Rate this Entry
by , 11-11-2011 at 06:31 PM (627 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

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

Java Code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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

		try {
			inputStream = new FileReader("CopyCharactersStreams.java");
			outputStream = new FileWriter("CopyCharacters.java");

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

Submit "Character Streams" to Facebook Submit "Character Streams" to Digg Submit "Character Streams" to del.icio.us Submit "Character Streams" to StumbleUpon Submit "Character Streams" to Google

Comments