title: Deleting a file using delete() - Java
body: <p>My code makes use of <code>BufferedReader</code> to read from a file [main.txt] and <code>PrintWriter</code> to write to a another temp [main.temp] file. I close both the streams and yet I was not able to call <code>delete()</code> method on the <code>File</code> object associated with [main.txt]. Only after calling <code>System.gc()</code> after closing both the stream was I able to delete the <code>File</code> object.</p>
  
  <pre><code>public static boolean delete (String str1, String str2, File FileLoc)
  {
      File tempFile = null;
      BufferedReader Reader = null;
      PrintWriter Writer = null;
  
      try
      {
          tempFile = new File (FileLoc.getAbsolutePath() + ".tmp");
          Reader = new BufferedReader(new FileReader(FileLoc));
          Writer = new PrintWriter(new FileWriter(tempFile));
          String lsCurrLine = null;
  
          while((lsCurrLine = Reader.readLine()) != null)
          {
              // ...
              // ...
  
              if (true)
              {
                  Writer.println(lsCurrLine);
                  Writer.flush();
              }
          }
  
          Reader.close();
          Writer.close();
          System.gc();
      }
      catch(FileNotFoundException loFileExp)
      {
          System.out.println("\n File not found . Exiting");
          return false;
      }
      catch(IOException loFileExp)
      {
          System.out.println("\n IO Exception while deleting the record. Exiting");
          return false;
      }
  }
  </code></pre>
  
  <p>Is this reliable? Or is there a better fix?</p>