The PrintWriter is another very convenient I/O class; it makes writing text to a file as easy as writing
text to the display. To create a PrintWriter that is associated with a file, you simply pass the name of the
file to the constructor. 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 ) {
System.err.println( "I/O error: " + e.getMessage() );
}
}
}
No comments:
Post a Comment