Question

I am trying to append some strings to a file every 5 seconds but I am having some problems.

My Java code is:

File file = new File("MyFile.txt");

FileWriter outFile = new FileWriter(file);

final PrintWriter out = new PrintWriter(outFile);

new Timer().scheduleAtFixedRate(new TimerTask()
{
    public void run()
    {
        out.println("Test string...");
    }, 0, 5 * 1000);
}

out.close();

but I have noticed that my file is always empty: it doesn't write anything!

I think my problem is in the TimerTask class but I can't solve it.

Is there a better way to write a file every N seconds?

Was it helpful?

Solution

timer is run in different thread so the file writer is closed first.

OTHER TIPS

Is that literally your code? It's not going to work because you close the output stream immediately after scheduling the timer task. When the task is run, the output stream is already closed and can't be written to anymore.

Make sure you don't close the output stream before you're writing data to it.

You closed the OutputStream.

Also I would use apache commons-io FileUtils, it makes life much easier dealing with File IO.

http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top