Skip to content
Advertisement

Clear Contents of a .txt file which is already being used in Java Program

FileOutputStream fileOutputStream = new FileOutputStream("CustomLogsOutput.txt");
PrintWriter logsPrintStream = new PrintStream(fileOutputStream);

This is the code that I am using to make an Object of PrintWriter which, as the name suggest, is used to dump logs in a file.

Now the logs are very large, and I am using this program on a free server, where we have storage limits. It might get big enoungh in 30 days, that I might run into storage issues.

Althogh, it is not a good practice, but for other reasons too, i want to make a function which, when called, will clear the contents of the log file CustomLogsOutput.txt. But I don’t want to close the PrintWriter at all. Neither can i afford to delete the file, otherwise PrintWriter might give an FileNotFoundException.

How can I clear the content of the file CustomLogsOutput.txt that will just clear the file and not affect any other part of the program?

Till now, this file is accessed only by the code provided above.

Advertisement

Answer

Just close the PrintWriter and create a new instance using the same file name.

PrintWriter logsPrintStream = new PrintWriter("CustomLogsOutput.txt");
/*
 * When you want to truncate the file then execute the following code.
 */
logsPrintStream.close();
logsPrintStream = new PrintWriter("CustomLogsOutput.txt");

According to the javadoc:

Parameters:
fileName – The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement