How to delete the content of a log file using Java code

8k views Asked by At

I need to clear the content of a certain log file in the server which is running Linux. I need to do it by calling a method from my program which is running in a different server. Please help me out. My program is using Java technology, So I need a Java code for this.

2

There are 2 answers

0
AlexR On

Jigar is right. You can just delete the file. But probably better to configure the logging of the program that produces this log. I mean if for example the program that creates the log is written in java too and uses log4j configure the appropriate appender to start new file when the current arrives to certain threshold (by size). You can also configure how many historical log files to hold etc. So, probably you even do not have to remove the files using other program.

1
Daniel On

You can try something like:


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

// code

public static void clearFile(String fileLocation){ try{ BufferedWriter bw = new BufferedWriter(new FileWriter(fileLocation)); bw.write(""); bw.flush(); bw.close(); }catch(IOException ioe){ // You should really do something more appropriate here ioe.printStackTrace(); } }</pre></code>

Since FileWriters don't append unless you explicitly tell them to.