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 can you write formatted text to a file with PrintWriter? | ComputerScienceOne | Bifalgorithm | Bifalgorithm