How to write to a text file

Common methods of the PrintWriter class:

Method Throws Description
print(argument) None Writes the character representation of the argument type to the file
println(argument) None Writes the character representation of the argument type to the file and presents a new line
flush() IOException Flushes any data that's in the buffer to the file.
close() IOException Flushes any data that's in the buffer to the file and closes the stream.

Example 1: Code that appends a sring and an object to a text file

// open an ouput stream for appending to the text file
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter("log.txt", true)));
// write a string and an object to the file
out.print("This application was run on ");
out.print(today);

Example 1: Code that writes a Product object to a delimited text file

// open an ouput stream for overwriting a text file
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write the Product object to the file
out.print(product.getCode() + "\t");
out.print(product.getDescription() + "\t");
out.print(product.getPrice() + "\t");
// flush data to the file and close the output stream
out.close();

Descriptions:

  • To write a character representation of a data type to an output stream, you use the print and println.

Warning:

  • To prevent data from being lost, you should alwasy close the stream when you're done using it.

More info can be found here: http://www.j2ee.me/javase/6/docs/api/java/io/PrintWriter.html