How to use PrintWriter in Java?

To use PrintWriter in Java, first create it with new, then call println, finally call close when you are done.

For example, this is will print Hello World! to the document.txt file in the /Users/whaadev directory:

try {
  PrintWriter writer = new PrintWriter("/Users/whaadev/document.txt");
  writer.println("Hello World!");
  writer.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

Don't forget that PrintWriter will not create folders for you. All folders along the path have to exist, otherwise it will throw FileNotFoundException.