My code makes use of BufferedReader to read from a file [main.txt] and PrintWriter to write to a another temp [main.temp] file. I close both the streams and yet I was not able to call delete() method on the File object associated with [main.txt]. Only after calling System.gc() after closing both the stream was I able to delete the File object.
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;
}
}
Is this reliable? Or is there a better fix?
@user183717 – that code you posted is clearly not all of the relevant code. For instance, those “…”‘s and the fact that
File.delete()is not actually called in that code.When a stream object is garbage collected, its finalizer closes the underlying file descriptor. So, the fact that the delete only works when you added the
System.gc()call is strong evidence that your code is somehow failing to close some stream for the file. It may well be a different stream object to the one that is opened in the code that you posted.Properly written stream handling code uses a
finallyblock to make sure that streams get closed no matter what. For example:If you don’t follow that pattern or something similar, there’s a good chance that there are scenarios where streams don’t always get closed. In your code for example, if one of the
readorwritecalls threw an exception you’d skip past the statements that closed the streams.No.
gc()call.System.gc()will notice that the stream is unreachable. Hypothetically, the stream object might be tenured, and callingSystem.gc()might only collect the Eden space.Yes. Fix your application to close its streams properly.