简体   繁体   English

使用RandomAccessFile删除Java 6文件

[英]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 . 我真的很失望地讨论类似的Java 6文件删除问题,并且无法在flie删除Post1Post2的这些类似帖子上找到解决方案。

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 . 我正在开发一个从FTP服务器下载文件的应用程序。下载是通过获取流,从该流读取并将其写入文件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. 您需要在finally块中关闭资源,以便始终将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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