Unpacking zip files in Java that cause a “java.uti

2019-06-02 19:22发布

I have a zip file (that is downloaded from an ownCloud instance) and can not be unpacked using the Java libraries (java version "1.8.0_66") from java.util.zip. If I try to do so, the following exception is thrown:

java.util.zip.ZipException: invalid LOC header (bad signature)

When issuing a Linux 'file' command, it outputs the following:

so-example.zip: Zip archive data, at least v3.0 to extract

After some trial and error I found out, that files, that are supposed to be unzippable by "v2.0", can be processed by Java without any issues.

A minimal example for the code used for unpacking is the following:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class PlaygroundZip{
    public static void main(String[] args) {
        String filename = "/tmp/so-example.zip";
        byte[] buffer = new byte[1024];

        try {
            ZipFile zipFile = new ZipFile(filename);
            Enumeration entries = zipFile.entries();
            while(entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry)entries.nextElement();
                String currName = entry.getName();

                System.out.println("File: " + currName);

                if(entry.isDirectory()) {
                    new File(currName).mkdirs();
                } else{
                    InputStream zis = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(currName);             

                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();  
                }
            }
            zipFile.close();
        } catch (IOException ioe) {
            System.err.println("Unhandled exception:");
            ioe.printStackTrace();
        }

    }
}

How can I process these files with standard Java libraries or any other method?

标签: java unzip
1条回答
等我变得足够好
2楼-- · 2019-06-02 20:06

The only way to unpack those files, I have found so far, is using a system command and use the "unzip" command line tool (Ubuntu 12.04 LTS, UnZip 6.00). As this is used in a server application it would be an acceptable hack, even though far away from being elegant.

Process p = Runtime.getRuntime().exec("unzip " + filename + " -d /tmp/mydir");
查看更多
登录 后发表回答