Text and Binary Files
Text files
Write to a text file
How to write to a text file
- To write a character representation of a data type to an output stream, you use the print and println methods of the PrintWriter class.
- If you supply an object as an argument, these methods will call the toString method of the object.
- To create a delimited text file, you delimit the records in the file with one delimiter, such as a new line character, and you delimit the fields of each record with another delimiter, such as a tab character.
- To prevent data from being lost, you should always close the stream when you're done using it. Then, the program will flush all data to the file before it closes the stream.
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 followed by the new line character. If the autoflush feature is turned on, this also flushes the buffer. |
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. |
Code that appends a string and an object to a text file
// open an output 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 "); Date today = new Date(); out.println(today); // flush data to the file and close the output stream out.close();
Code that writes a Product object to a delimited text file
// open an output 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.println(product.getPrice()); // flush data to the file and close the output stream out.close();