23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Java</strong> I/O<br />

Admittedly, this is a contrived example. If you really needed to do this, you could just call the<br />

string's toCharArray() method and loop through that (or even the string itself) using its<br />

charAt() method.<br />

15.7 Reading and Writing Files<br />

You've already learned how to chain an OutputStreamWriter to a FileOutputStream and<br />

an InputStreamReader to a FileInputStream. Although this isn't hard, <strong>Java</strong> provides two<br />

simple utility classes that take care of the details, java.io.FileWriter and<br />

java.io.FileReader.<br />

15.7.1 FileWriter<br />

The FileWriter class is a subclass of OutputStreamWriter that writes text files using the<br />

platform's default character encoding and buffer size. If you need to change these values,<br />

construct an OutputStreamWriter on a FileOutputStream instead.<br />

public class FileWriter extends OutputStreamWriter<br />

This class has four constructors:<br />

public FileWriter(String fileName) throws <strong>IO</strong>Exception<br />

public FileWriter(String fileName, boolean append) throws <strong>IO</strong>Exception<br />

public FileWriter(File file) throws <strong>IO</strong>Exception<br />

public FileWriter(FileDescriptor fd)<br />

The first constructor opens a file and positions the file pointer at the beginning of the file. Any<br />

text in the file is overwritten. For example:<br />

FileWriter fw = new FileWriter("36.html");<br />

The second constructor allows you to specify that new text is appended to the existing<br />

contents of the file rather than overwriting them by setting the second argument to true. For<br />

example:<br />

FileWriter fw = new FileWriter("36.html", true);<br />

The third and fourth constructors use a File object and a FileDescriptor, respectively,<br />

instead of a filename to identify the file to be written to. Any pre-existing contents in a file so<br />

opened are overwritten.<br />

No methods other than the constructors are declared in this class. You use the standard<br />

Writer methods like write(), flush(), and close() to write the text in the file.<br />

15.7.2 FileReader<br />

The FileReader class is a subclass of InputStreamReader that reads text files using the<br />

platform's default character encoding. If you need to change the encoding, construct an<br />

InputStreamReader chained to a FileInputStream instead.<br />

public class FileReader extends InputStreamReader<br />

372

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!