2

I am really disappointed to discuss a similar java 6 file deletion issue and not being able to find a solution on these similar posts on flie deletion Post1 and Post2.

I am working on an application which downloads a file from the FTP Server.This downloading is achieved by obtaining the stream , reading from this stream and writing it to a file RandomAccessFile. In case of corrupt downloads,I wish to delete the file on the disk.

I am unable to delete the file manually or via the application.It is very obvious that some file handler still has the lock for the file due to which file deletion is a failure. However,I cant understand which file handlers possesses the file lock as I have made sure that I close all the file and the stream objects.

Finally,the code snippet

public class OprDownload extends Observable implements Runnable 
 {
   public void run()
   {
    //Code to connect to ftp,obtain the stream and write to a file
    if (download complete)
    {

        if(mwwObjFile!=null)
       {
          mwwObjFile.close();

       }
       if(stream!=null)
       {
          stream.close();
       }
       if(compareChecksum())//If checksum match success
       {
           updateDownloadDetails();
           cwwIntStatus = COMPLETE;
       }
       else
       {
           cwwIntStatus = CHECKSUM_FAIL;
           deleteCorruptUpdateFromDownloadsFolder();
       }
     }
}

    public void deleteCorruptUpdateFromDownloadsFolder() 
    {
         String fileOndisk = "FileName";
         File mwwFileToBeDeleted = new File(fileOndisk );

        if(mwwFileToBeDeleted .exists())
        {
            System.out.println("File Deleted"+mwwFileToBeDeleted .delete());
        }

    }
}
Community
  • 1
  • 1
sherry
  • 352
  • 2
  • 8
  • 17

1 Answers1

1

If you throw any unchecked exception here, the file(s) will not be closed.

public void run()
{
    //Code to connect to ftp,obtain the stream and write to a file
    if (download complete) // throws an unchecked exception and exits run()
    {

You need to close your resources in a finally block so they will always be closed.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Yes I have closed the resources in the finally block in the actual code.Have edited it here to make the snippet shorter.Thanks anyway. – sherry Dec 27 '11 at 11:29