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?
timer is run in different thread so the file writer is closed first.