nuwan.danushka
nuwan.danushka

Reputation: 57

unzip file by using java

public void unZipFile(String zipFileLocation, String outputFolder) {
    logger.info("ZipFileLocation: "+zipFileLocation);
    logger.info("OutputLocation: "+outputFolder);

    File dir = new File(outputFolder);
    // create output directory if it doesn't exist
    if(!dir.exists()) dir.mkdirs();
    FileInputStream fis;
    //buffer for read and write data to file
    byte[] buffer = new byte[1024];
    try {
        fis = new FileInputStream(zipFileLocation);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
        while(ze != null){
            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            System.out.println("Unzipping to "+newFile.getAbsolutePath());
            //create directories for sub directories in zip
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            //close this ZipEntry
            zis.closeEntry();
            ze = zis.getNextEntry();
        }
        //close last ZipEntry
        zis.closeEntry();
        zis.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This is a code that i have used to unzip folder to specific location. i am getting following exception once i execute this process. please advice why this issue arise?

 java.util.zip.ZipException: invalid entry size (expected 3173388 but got 3173359 bytes)
 [java]     at java.util.zip.ZipInputStream.readEnd(ZipInputStream.java:403)
 [java]     at java.util.zip.ZipInputStream.read(ZipInputStream.java:195)
 [java]     at java.io.FilterInputStream.read(FilterInputStream.java:107)
 [java]     at com.shipxpress.irf.server.service.impl.IrfServiceImpl.unZipFile(IrfServiceImpl.java:1020)
 [java]     at com.shipxpress.irf.server.service.impl.IrfServiceImpl.executeFileTransferProcess(IrfServiceImpl.java:1310)
 [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 [java]     at java.lang.reflect.Method.invoke(Method.java:606)

Really appreciate if anyone can help me to fix this issue

Thanks,

Upvotes: 0

Views: 9626

Answers (5)

amralieg
amralieg

Reputation: 123

I had similar problem, and I modifed the code to work, it turn out the code does not distinguish between a file and a folder and that's that check that I added.

    public static void unzipFile(String zipFilePath, String destDir)
    {
        File dir = new File(destDir);
        // create output directory if it doesn't exist
        if (!dir.exists())
            dir.mkdirs();
        FileInputStream fis;
        // buffer for read and write data to file
        byte[] buffer = new byte[1024];
        try
        {
            fis = new FileInputStream(zipFilePath);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry ze = zis.getNextEntry();
            while (ze != null)
            {
                try
                {
                    String fileName = ze.getName();
                    File newFile = new File(destDir + File.separator + fileName);
                    System.out.println("Unzipping to " + newFile.getAbsolutePath());
                    // create directories for sub directories in zip
                    new File(newFile.getParent()).mkdirs();
                    if(ze.isDirectory()) // check if this is a diectory or file
                    {
                        newFile.mkdirs();
                    }
                    else
                    {
                        FileOutputStream fos = new FileOutputStream(newFile);
                        int len;
                        while ((len = zis.read(buffer)) > 0)
                        {
                            fos.write(buffer, 0, len);
                        }
                        fos.close();
                    }
                    // close this ZipEntry
                    zis.closeEntry();
                }
                catch(Exception e)
                {
                    System.err.println(e.getMessage());
                }
                ze = zis.getNextEntry();
            }
            // close last ZipEntry
            zis.closeEntry();
            zis.close();
            fis.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

Upvotes: 0

Varun A M
Varun A M

Reputation: 1162

Instead of hard-coding it as

byte[] buffer = new byte[1024];

Try below.

byte[] buffer = new byte[(int) ze.getSize()];

You can find the detailed tutorial here.

https://www.youtube.com/watch?v=hzBlCnkhKog

Upvotes: 0

KuLdip PaTel
KuLdip PaTel

Reputation: 1069

Use this library www.lingala.net/zip4j/

add this jar file in lib folder of app.

check your import like that

import net.lingala.zip4j.core.ZipFile;

import net.lingala.zip4j.exception.ZipException;

import net.lingala.zip4j.model.FileHeader;

use below method like this

unzip("/sdcard/file.zip","/sdcard/unzipFolder")


  public static void unzip(String Filepath, String DestinationFolderPath) {

        try {
            ZipFile zipFile = new ZipFile(Filepath);
            List fileHeaders = zipFile.getFileHeaders();
            for(int i=0;i<fileHeaders.size();i++) {
                FileHeader  fileHeader=(FileHeader) fileHeaders.get(i);
                String fileName = fileHeader.getFileName();
                Log.d(TAG,fileName);
                if (fileName.contains("\\")) {
                    fileName=fileName.replace("\\","\\\\");
                    String[] Folders=fileName.split("\\\\");
                    StringBuilder newFilepath=new StringBuilder();
                    newFilepath.append(DestinationFolderPath);
                    for (int j=0;j<Folders.length-1;j++){
                        newFilepath.append(File.separator);
                        newFilepath.append(Folders[j]);
                    }
                    zipFile.extractFile(fileHeader, newFilepath.toString(),null,Folders[Folders.length-1]);
                }else {
                    zipFile.extractFile(fileHeader,DestinationFolderPath);
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        }
    }

Upvotes: 1

P S M
P S M

Reputation: 1161

I could think of these reasons:

  1. The file could simply be corrupt.Try opening the file with a zip utility.
  2. There could be a problem with the encoding of the text file.
  3. The file needs to be read/transferred in "binary" mode.
  4. There could be an issue with the line ending \n or \r\n

Upvotes: 0

Jerome L
Jerome L

Reputation: 637

I don't exactly know why it fails in your case (invalid zip file?), but I would recommend:

  • First, use Java 7 java.nio.file.Path API which is far better than the old java.io.File.
  • Second, It's way more convenient to use Apache Commons Compress when dealing with compressed files. It's way more flexible as it can handle zip, bzip, 7zip, pack200 and more formats,
  • Last, perform .close() operations in a try ... finally block to avoid unclosed streams in case of exception.

Upvotes: 0

Related Questions