Reading Writing Text  «Prev  Next»


Lesson 13OutputStreamWriter
ObjectiveInvestigate how the OutputStreamWriter subclass works.

Java OutputStreamWriter

The most important concrete subclass of the abstract Writer class is java.io.OutputStreamWriter. This class implements the abstract methods of Writer and sends written data to an output stream specified when the writer is constructed. There are two constructors in this class:

public OutputStreamWriter(OutputStream out, String enc) throws UnsupportedEncodingException 
public OutputStreamWriter(OutputStream out)

To attach an OutputStreamWriter to System.out with the default encoding, (generally ISO Latin-1), use this code:
OutputStreamWriter osw = new OutputStreamWriter(System.out);

On the other hand if you wanted to write a file encoded in the Macintosh Symbol font, you might do this:
FileOutputStream fos =  new FileOutputStream("symbol.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "MacSymbol");

OutputStreamWriter Class

java.io.Writer is an abstract class. Its most basic concrete subclass is OutputStreamWriter:
public class OutputStreamWriter extends Writer

Its constructor connects a character writer to an underlying output stream:
public OutputStreamWriter(OutputStream out)
public OutputStreamWriter(OutputStream out, String encoding) throws
UnsupportedEncodingException

The first constructor assumes that the text in the stream is to be written using the platform's default encoding. The second constructor specifies an encoding. There's no easy way to determine which encodings are supported, but the ones listed in Table B.4 in Appendix B, are supported by most VMs. For example, this code attaches an OutputStreamWriter to System.out with the default encoding:
OutputStreamWriter osw = new OutputStreamWriter(System.out);

The default encoding is normally ISO Latin-1, except on Macs, where it is MacRoman. Whatever it is, you can find it in the system property file.encoding:
String defaultEncoding = System.getProperty("file.encoding");

On the other hand, if you want to write a file encoded in ISO 8859-7 (ASCII plus Greek) you might do this:
FileOutputStream fos = new FileOutputStream("greek.txt");
OutputStreamWriter greekWriter = new OutputStreamWriter(fos, "8859_7");

The write() methods convert characters to bytes according to a specified character encoding and write those bytes onto the underlying output stream:
public void write(int c) throws IOException
public void write(char[] text, int offset, int length) throws IOException
public void write(String s, int offset, int length) throws IOException