Clear contents of a file

Let's say that I have a Java program running, with its standard output directed to a log file:

java MyJavaProgram > stdout.log

This program will keep on running. To ensure that the log file does not grow very big, I am trying to write a script to remove the contents of the file. I tried two ways:

echo "" > stdout.log

cp /dev/null stdout.log

But in both cases, they are writting a lot of null characters into the log file. The file does not shrink at all. The contents are merely replaced with null characters.

How can I achive what I want? Thanks.
Who is Participating?
Brian UtterbackConnect With a Mentor Principle Software EngineerCommented:
The problem you were seeing in the first instance is that the java program's file pointer continues to point to the same block that it is writing to even after you have truncated the file. Thus when it writes again, it writes to the same block it would have written to before you truncated. This actually does not fill in the file with nulls, it only appears to. It actually transforms the file into a sparse file. It will not actually allocate storage blocks for the intervening null blocks. If space is your only concern, then this may be enough.

You can see why converting to >> work though. The >> says to append to the file, which means that all blocks are written to the end of the file. This means that once the file is truncated, the end of the file becomes the beginning as it were.
You could remove the file then "touch" it

rm -f stdout.log
touch stdout.log

This is probably not the most ideal scenario as you "may" need to reset user / group permissions.
You can only reliably truncate a file when it's not being written to.

Do you have any control over the java program, ie: can you restart it?

Easiest way to truncate a file is

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

integrosysAuthor Commented:
Thanks guys. Actually I found that these two lines:

echo "" > stdout.log
cp /dev/null stdout.log

will work if the Java program is started this way instead:

java MyJavaProgram >> stdout.log
Hi blu, what is a sparse file? You said that it does not allocate storage blocks. But when I use the ls command, I notice that the file size never decreases.
If you use

du -sh file

You'll see the real size of the file.
Brian UtterbackPrinciple Software EngineerCommented:
Or use "ls -ls"
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.