How to clear a file in Java?

To clear a file in Java, write an empty string to that file with PrintWriter.write method.

For example, this is how you can clear the document.txt file in the /Users/whaadev directory:

PrintWriter writer = new PrintWriter("/Users/whaadev/document.txt");
writer.print("");
writer.close();