Reading Writing Text  «Prev  Next»


Lesson 11The write() methods of the Writer class
ObjectiveExamine the methods of the Writer class used to write characters.

Java write() Methods(Writer class)

The basic write() method of the Writer class writes a single two-byte character with a value between 0 and 65,535. The value is taken from the two low-order bytes of the argument c.

public void write(int c) throws IOException

You can also write an array of characters, a subarray of characters, a string, or a substring.
public void write(char c[]) throws IOException

public abstract void write (char c[], int offset, int length) throws IOException

public void write(String s) throws IOException

public void write(String s, int offset, int length) throws IOException

The default implementations of these four methods convert their first argument into an array of chars and pass that to write(char[] text, int offset, int length).
Specific subclasses may provide more efficient implementations of these methods.

java.io.Writer Class

The Writer class is abstract, just like OutputStream is abstract. You will not have any pure instances of Writer that are not also instances of some concrete subclass of Writer. However, many of the subclasses of Writer differ primarily in the targets of the text they write, just as many concrete subclasses of OutputStream differ only in the targets of the data they write. Most of the time you don't care about the difference between FileOutputStream and ByteArrayOutputStream. Similarly, most of the time you won't care about the differences between FileWriter and StringWriter. You'll just use the methods of the common superclass, java.io.Writer.

You use a writer almost exactly as you use an output stream. Rather than writing bytes, you write chars. The write() method writes a subarray from the char array text starting at offset and continuing for length characters:
public abstract void write(char[] text, int offset, int length)
throws IOException

For example, given some Writer object w, you can write the string Testing 1-2-3 like this:
char[] test = {'T', 'e', 's', 't', 'i', 'n', 'g', ' ',
'1', '-', '2', '-', '3'};
w.write(test, 0, test.length);

This method is abstract. Concrete subclasses that convert chars into bytes according to a specified encoding and write those bytes onto an underlying stream must override this method. An IOException may be thrown if the underlying stream's write() method throws an IOException. You can also write a single character, an entire array of characters, a string, or a substring: