Sams Teach Yourself C in 21 Days

(singke) #1
More Java Techniques 747

BD6


Writing Text Files ..........................................................................................


To write text to a file, use the FileWriterclass. The syntax for creating a FileWriter
object is
FileWriter outFile = new FileWriter(filename, append);
Filenameis the name (including path, if required) of the file. The optional append
applies only if filenamealready exists. Set appendtotrueif the new data is to be
appended to the file,falseto overwrite the file. Then, create a BufferedWriterobject
based on the FileWriterobject:
BufferedWriter buff = new BufferedWriter(outFile);
Now you can use the BufferedWriterobject’s writemethod to output text to the file:
buff.write(text);
Textis a type Stringcontaining the text to output. New lines are not started automati-
cally. If you want the text to start on a new line, put the new line character (\n) at the
start of the text. The program in Listing B6.2 demonstrates writing text to a file.

LISTINGB6.2 writing.java. Writing text to a file
1: import java.lang.System;import java.io.*;
2:
3: public class WriteTextFile {
4: public static void main(String args[]) {
5: String s;
6: BufferedReader kb;
7: boolean fileError = false;
8:
9: kb = new BufferedReader(new InputStreamReader(System.in));
10: try {
11: FileWriter outFile = new FileWriter(“c:\\output.txt”);
12: BufferedWriter buff = new BufferedWriter(outFile);
13: System.out.println(“Enter lines of text to put in the file.”);
14: System.out.println(“Enter a blank line when done.”);
15: boolean done = false;
16: while (!done) {
17: s = kb.readLine();
18: if (s.length() > 0 ) {
19: s = s + “\n”;
20: buff.write(s);
21: }
22: else
23: done = true;
24: }
25: buff.close();

41 448201x-Bonus6 8/13/02 11:23 AM Page 747

Free download pdf