Java Reference
In-Depth Information
// Create a Writer object from OutputStream using the "US-ASCII" encoding
Writer writer = new OutputStreamWriter(oso, "US-ASCII");
You do not have to write only a character at a time or a character array when using a writer. It has methods that let
you write a String and a CharSequence object.
Let's write another stanza from the poem Lucy by William Wordsworth to a file and read it back into the program.
This time, you will use a BufferedWriter to write the text and a BufferedReader to read the text back. Here are the
four lines of text for the stanza:
And now we reach'd the orchard-plot;
And, as we climb'd the hill,
The sinking moon to Lucy's cot
Came near and nearer still.
The text is saved in a luci4.txt file in the current directory. Listing 7-32 illustrates how to use a Writer object
to write the text to this file. You may get a different output when you run the program because it prints the path of the
output file that depends on the current working directory.
Listing 7-32. Using a Writer Object to Write Text to a File
// FileWritingWithWriter.java
package com.jdojo.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileWritingWithWriter {
public static void main(String[] args) {
// The output file
String destFile = "luci4.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(destFile))) {
// Write the text to the writer
bw.append("And now we reach'd the orchard-plot;");
bw.newLine();
bw.append("And, as we climb'd the hill,");
bw.newLine();
bw.append("The sinking moon to Lucy's cot");
bw.newLine();
bw.append("Came near and nearer still.");
// Flush the written text
bw.flush();
System.out.println("Text was written to " +
(new File(destFile)).getAbsolutePath());
}
catch (FileNotFoundException e1) {
FileUtil.printFileNotFoundMsg(destFile);
 
Search WWH ::




Custom Search