Then you can write to the file simply using the print() and println() methods you
have learned to use for writing to the display.
A PrintWriter can be used with any output stream, but a very common use is to make it very easy to
write formatted text to a file. Here is a simple program that reads lines of text typed at the keyboard, and writes
the same text into a file using a PrintWriter. Using the println() method, this program adds a line
number at the front of each line as it writes the line to the file.
import java.io.*; //PrintWriter is here
import java.util.*; //Scanner is here
public class PrintToFile{
public static void main( String[] args) {
PrintWriter myWriter;
Scanner sc;
String lineOfData;
String fileName;
int lineNumber;
try {
System.out.print("Enter file name: " );
sc = new Scanner( System.in );
fileName = sc.nextLine();
myWriter = new PrintWriter( fileName );
System.out.println( "Now enter lines of text." );
System.out.println( "When you are done, " +
"type only Cntrl/z (EOF) on the line." );
lineNumber = 1;
while( sc.hasNextLine() ) {
lineOfData = sc.nextLine();
myWriter.println( lineNumber + ". " + lineOfData );
lineNumber++;
}
myWriter.close();
}
catch( IOException e ) {
92 PROGRAMMING IN JAVA [CHAP.
Pages:
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247