Showing posts with label Throws. Show all posts
Showing posts with label Throws. Show all posts

Monday, May 28, 2012

PrintWriter


DOWNLOAD THE CODE: PrintToFile.java

The PrintWriter class contains 2 very useful methods:
  • print(String)
  • println(String)
These methods write a String to a file.
The println method adds the end-of-line character after the string.

The constructor of the PrintWriter class accepts a file to write to. As such, a File object has been declared. The constructor of the File object accepts a String file path of the file's location. It is interesting to note that if the file has not already been created, the PrintWriter will create it automatically.

The example below contains 2 loops. The first loop writes the numbers 1-10 (using the loop counter) to data.txt using the print() method. As such, each number is written immediately after the last. The second loop also writes the numbers 1-10 to data.txt but uses the println() method so that each number is written on a new line.


Here is the output:




Throws FileNotFoundException. If you do not implement exception handling for this exception, the compiler will force you to rethrow it.

And if you want to read text file from a file, here's a post about the Scanner class.

"PrintWriter (Java Platform SE 7 )" ( http://bit.ly/LsOVki )

Here's a cat: