Delete zip file after unpacking in java

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

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

Edit:
Rule "Directory must be empty before deletion .." does it apply to a zip file?

My file to unzip files


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


    }

} 

+3
source share
4 answers

If it file.delete()returns false, then I assume that the other process has an open mail file - or perhaps even your own process.

  • Make sure you have the right path, for example. what returns file.exists()?
  • Make sure that you have permission to delete the file as the user running your application.
  • , (, ?)
  • , , .
+5

, ZipFile.

, :

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

This very often happens when you try to delete a created file. Be sure to use the closeFileWriter that you used to create the unzipped file.

If you cannot figure out where to close the file, a better option would be to make a call file.deleteOnExit()that should succeed, even if you accidentally leave a few openable files.

0
source

Using: FileUtils.delete(yourFile);

This fixed my problem.

0
source

Source: https://habr.com/ru/post/1796744/


All Articles