title: How to overwrite a file in java
body: <p>In my program, I am trying to read the file and then trying to overwrite the file using txtFile method. f is the file which I am reading and doing operations on its contents and now want to replace its contents with the new string, s.</p>
  
  <pre><code>                    String s = obj1.method(string);
                      toFile(s, f);
  </code></pre>
  
  <p>my txtFile method is below:</p>
  
  <pre><code>public static void txtFile(String cnvrt, File file)                 
  {   
      try
      {
          PrintWriter printWriter = new PrintWriter (file);
          printWriter.print(cnvrt);
          printWriter.close ();           
      }
      catch(Exception exception)
      {
          exception.printStackTrace();
      }
  }
  </code></pre>
  
  <p>While doing this way, my original content is erased and the file gets empty. Please suggest me how to overwrite the same file using printWriter class? Even when I am using the <code>FileWriter</code> and <code>BufferedReader</code>, I obtained the empty file. Can somebody explain me this behavior?</p>