Concept
How can you write formatted text to a file with PrintWriter?
ComputerScienceOne / File Output
"There are several ways to achieve file output, but we’ll look at the simplest and most useful way. Java provides a PrintWriter class which offers many convenient methods for writing primitive and String types in a formatted manner. It has the usual print() and println() methods that we are familiar with as well as a printf() style method for formatting. PrintWriter is also buffered, depending on how you instantiate it, it might “flush” its buffer after every endline character or you may do it manually by invoking the flush() method.\n\nint x = 10;\n\ndouble pi = 3.14;\n\nPrintWriter pw = null;\n\ntry {\n\npw = new PrintWriter(new File(\"data.txt\"));\n\n} catch(FileNotFoundException fnfe) {\n\nthrow new RuntimeException(fnfe);\n\n}\n\npw.println(\"Hello World!\");\n\npw.println(x);\n\npw.printf(\"x = %d, pi = %f\n\n\", x, pi);\n\npw.close();\n\nThe close() method will conveniently close all the underlying resources and flush the buffer for us, writing any buffered data to the file. In addition, PrintWriter implements AutoCloseable and so it can be used in a try-catch-with resources statement. Another “convenience” of PrintWriter is that is “swallows” exceptions (just as the Scanner class did). That means we don’t have to deal explicitly with the checked IOException s that the underlying class(es) throw as the PrintWriter silently catches them (though doesn’t handle them). However, this can also be viewed as a disadvantage in that if we want to do error handling, we need to manually check if there was an error (using checkError() ). The PrintWriter class is intended mostly for formatted output. It does not provide a way to write binary data to an output file."
Related Ideas
- How do fprintf() and fscanf() read from and write to plaintext files?ComputerScienceOne · Plaintext Files
- How do buffered and unbuffered file input/output differ?ComputerScienceOne · Buffered and Unbuffered
- When should data be stored as binary or text files?ComputerScienceOne · Buffered and Unbuffered
- How can a Scanner read input from a file?ComputerScienceOne · File Input
- How does try-with-resources simplify closing file input resources?ComputerScienceOne · File Input
- When should you use specialized classes for binary file input?ComputerScienceOne · File Input
- How are files read, written, and properly managed?ComputerScienceOne · Paths
- How should you close files in C?ComputerScienceOne · Closing Files