O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The 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 2.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[] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required