简体   繁体   中英

Java 6 File Deletion with RandomAccessFile

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());
        }

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM