Bridging byte streams to character streams on writing-side

The byte streams and character streams are incompatible for linking as the first one operates on 8-bit ASCII characters and the other on 16-bit Unicode characters. To link them explicitly, two classes exist in java.io package, InputStreamReader and OutputStreamWriter. Towards this functionality, we have seen earlier InputStreamReader that bridged (links) System.in, a byte stream, with the character stream BufferedReader (on reading-side) .

With OutputStreamWriter, the characters of 2-bytes are encoded (converted) into bytes of 1-byte (InputStreamReader does it other way – bytes to characters). Now in the following program, the OutputStreamWriter is used to link FileOutputStream (bye stream) with BufferedWriter (character stream).


FileOutputStream fostream = new FileOutputStream("yyy.txt");
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);

Observe, the FileOutputStream object fostream is linked (or chained) to BufferedWriter object bwriter using OutputStreamWriter object oswriter. With this chaining, file is opned with FileOutputStream and written with BufferedWriter.

bwriter.write(&quot:Use steps for&quot:);

The write() method of BufferedWriter writes a string to the file, yyy.txt.

Alternatively, we can specify the encoding scheme also with OutputStreamWriter as follows.

FileOutputStream fis = new FileOutputStream("pqr.txt");
OutputStreamWriter osw = new OutputStreamWriter(fis, "8859_5");

The OutputStreamWriter constructor throws a checked exception “"UnsupportedEncodingException" when the encoding scheme included does not exist. We know earlier, the FileOutputStream constructor throws "FileNotFoundException".

Leave a Reply

Your email address will not be published. Required fields are marked *