开发者

Delete a zip file after unzip in java

开发者 https://www.devze.com 2023-02-15 09:30 出处:网络
How to delete a zip file in java?file.delete method returns false. Why? File file = new File(\"/mibook/\"+mFilename+\"/\"+mZipname.toString());

How to delete a zip file in java? file.delete method returns false. Why?

File file = new File("/mibook/"+mFilename+"/"+mZipname.toString());
boolean deleted = file.delete();

edit:

Rule "Directory should empty before deletion.." does it apply for zip file?

My file unzipping code


   public void unzip() throws IOException { 
        FileInputStream fin=null;
        ZipInputStream zin=null;
        File file =null;
        ZipEntry ze ;
        FileOutputStream fout=null;
        try{ 
            System.out.println(_zipFile );
            System.out.println(_location);
            fin = new FileInputStream(_zipFile); 
            zin = new ZipInputStream(fin); 
            ze= null; 
            byte[] buffer = new byte[1024];
            int length;
            while ((ze = zin.getNextEntry()) != null) { 
                file = new File((_location +"/" + ze.getName()));
                file.getParentFile().mkdirs();
                 fout= new FileOutputStream(_location + ze.getName()); 
             开发者_开发技巧   while ((length = zin.read(buffer))>0) {
                    fout.write(buffer, 0, length);
                }
                zin.closeEntry(); 
                fout.close();

} zin.close(); }catch(Exception e) { Log.e("Decompress", "unzip", e); }

finally {

            fin.close();
            zin.close();
            fout.close();


    }

} 


You have to make sure you close your ZipFile.

For example I had:

ZipFile zFile = new ZipFile("blah");
//lots-o-code
zFile.close();
File file = new File("blah");
file.delete();


If file.delete() returns false, then my guess is that another process has the zip file open - or possibly even your own process.

  • Check that you've got the path correct, e.g. what does file.exists() return?
  • Check that you've got permission to delete the file as the user running your application
  • Check that you haven't got an open handle to the file within your code (e.g. have you just read from it and not closed the input stream?)
  • Check that you don't have the file opened in a desktop app


This is very common when attempting to delete a file that you've created. Be sure to close the FileWriter you used to create the unzipped file.

If you can't figure out where to close the file, your best bet may be to call file.deleteOnExit() which should succeed even if you accidentally leave a few file handles open.


Use : FileUtils.delete(yourFile);

This corrected my problem

0

精彩评论

暂无评论...
验证码 换一张
取 消