Java Reference
In-Depth Information
Display 10.1
Sending Output to a Text File (part 2 of 2)
15 {
16 System.out.println("Error opening the file stuff.txt.");
17 System.exit(0);
18 }
19 System.out.println("Writing to file.");
20 outputStream.println("The quick brown fox");
21 outputStream.println("jumps over the lazy dog.");
22 outputStream.close();
23 System.out.println("End of program.");
24 }
25 }
Sample Dialogue
Writing to file.
End of program.
F ILE stuff.txt (after the program is run.)
The quick brown fox
jumps over the lazy dog.
You can read this file
using a text editor.
Opening a Text File for Writing Output
You create a stream of the class PrintWriter and connect it to a text file for writing as follows.
SYNTAX
PrintWriter Output_Stream_Name ;
Output_Stream_Name =
new PrintWriter( new FileOutputStream( File_Name ));
EXAMPLE
PrintWriter outputStream = null ;
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
After this, you can use the methods println and print to write to the file.
When used in this way, the FileOutputStream constructor, and thus the PrintWriter
constructor invocation, can throw a FileNotFoundException , which is a kind of
IOException .
 
 
Search WWH ::




Custom Search