Moudiz
Moudiz

Reputation: 7377

Zip file not deleted even if I am getting its correct name and path

I am trying to delete a zip file after unziping. but I am not able to delete it:

if (file.getName().contains(".zip")) {
    System.out.println(file.getAbsolutePath()); // I am getting the correct path
    file.delete();
    System.out.println(file.getName()); // I am getting the correct name Script-1.zip
}

This is the full code

public class Zip4 {

    public static void main(String[] args) {
        File[] files = new File(args[0]).listFiles();

        for(File file : files)
        //  System.out.println(file.getName());
            //if(file.getName().contains("1400") && file.getName().contains(".zip"))
              extractFolder(args[0] + file.getName(), args[1]);
        DeleteFiles();

     //   for(File file : files)
                //  System.out.println("File:C:/1/"+ file.getName());

//      extractFolder(args[0]+file.getName(),args[1]);

    }

    private static void DeleteFiles()
    {
        File f = null;
        File[] paths;
        f = new File("D:/Copyof");
        paths = f.listFiles();

          for(File path:paths)
             {
                // prints file and directory paths
                if(path.getName().contains("J14_0_0RC") || path.getName().contains(".zip") || path.getName().contains(".log"))
                {

                     //System.out.println(path);
                     path.delete();
                }

             }
    }

    private static void extractFolder(String zipFile,String extractFolder) 
    {
        try
        {
            int BUFFER = 2048;
            File file = new File(zipFile);
            ZipFile zip = new ZipFile(file);
            String newPath = extractFolder;

            new File(newPath).mkdir();
            Enumeration zipFileEntries = zip.entries();

            // Process each entry
            while (zipFileEntries.hasMoreElements())
            {
                // grab a zip file entry
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();

                File destFile = new File(newPath, currentEntry);
                //destFile = new File(newPath, destFile.getName());
                File destinationParent = destFile.getParentFile();

                // create the parent directory structure if needed
                destinationParent.mkdirs();

                if (!entry.isDirectory())
                {
                    BufferedInputStream is = new BufferedInputStream(zip
                    .getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedOutputStream dest = new BufferedOutputStream(fos,
                    BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                    dest.flush();
                    dest.close();
                    fos.flush();
                    fos.close();
                    is.close();
                }

            }

            if(file.getName().contains(".zip"))
            {
                System.out.println(file.getAbsolutePath());
                file.delete();
                  System.out.println(file.getName());
            }
        }
        catch (Exception e) 
        {
            System.out.println("Error: " + e.getMessage());

        }
    }
}

Upvotes: 0

Views: 1211

Answers (1)

Gerald Mücke
Gerald Mücke

Reputation: 11132

ZipFile is a closeable resource. So either close() it once you're done in a finally block or create it with try-with-resources (since java7):

try(ZipFile zip = new ZipFile(file)){
  //unzip here
}
file.delete();

Apart from this, you should revisit this block

dest.flush();
dest.close();
fos.flush();
fos.close();
is.close();

which is quite prone to resource leaks. If one of the upper calls fails, all subsequent calls are not invoked, resulting in unclosed resources and resource leakage.

So best would be to use try-with-resources here, too.

try(BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
  //write the data
} //all streams are closed implicitly here

Or use an existing tool for that, for example Apache Commons IO IOUtil.closeQuietly(resource) or embedd every single call into

if(resource != null) {
  try{
     resource.close();
  } catch(IOException e){
     //omit
  }
}

You could also omit the call to flush() which is done implicitly when closing the resource.

Upvotes: 2

Related Questions