title: Writing a file in Java every 5 seconds with TimerTask
body: <p>I am trying to append some strings to a file every 5 seconds but I am having some problems.</p>
  
  <p>My Java code is:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>but I have noticed that my file is always empty: it doesn't write anything!</p>
  
  <p>I think my problem is in the TimerTask class but I can't solve it.</p>
  
  <p>Is there a better way to write a file every N seconds?</p>