java提取Zip文件

时间:2013-04-05 08:43:59

标签: java zip extract

我正在寻找一种提取Zip文件的方法。到目前为止,我已经尝试过java.util.zip和org.apache.commons.compress,但两者都输出了损坏的输出。

基本上,输入是一个包含一个.doc文件的ZIP文件。

java.util.zip:输出已损坏。 org.apache.commons.compress:输出空白文件,但大小为2 mb。

到目前为止,只有像Winrar这样的商业软件才能完美运行。是否有一个使用它的java库?

这是我使用java.util库的方法:

public void extractZipNative(File fileZip)
{
    ZipInputStream zis;
    StringBuilder sb;
    try {
        zis = new ZipInputStream(new FileInputStream(fileZip));
        ZipEntry ze = zis.getNextEntry();

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

        FileOutputStream fos = new FileOutputStream(this.tempFolderPath+ze.getName());

        int len;
        while ((len=zis.read(buffer))>0)
        {
            fos.write(buffer);
        }
        fos.flush();
        fos.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally 
    {
        if (zis!=null) 
        {
            try { zis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

非常感谢, 迈克

5 个答案:

答案 0 :(得分:2)

我认为您的输入可能会被一些“不兼容”的zip程序压缩,如7zip。 如果可以使用经典的WinZip等解压缩,请先尝试调查。

Javas zip处理能够很好地处理来自“兼容”拉链压缩器的压缩档案。

答案 1 :(得分:1)

我的代码中出错。我需要指定offset和bytes of bytes write。

答案 2 :(得分:1)

它对我有用

    ZipFile Vanilla = new ZipFile(new File("Vanilla.zip")); //zipfile defined and needs to be in directory
    Enumeration<? extends ZipEntry> entries = Vanilla.entries();// all (files)entries of zip file

    while(entries.hasMoreElements()){//runs while there is files in zip
        ZipEntry entry = entries.nextElement();//gets name of file in zip
        File folderw =new File("tkwgter5834");//creates new directory
        InputStream stream = Vanilla.getInputStream(entry);//gets input
        FileInputStream inpure= new FileInputStream("Vanilla.zip");//file input stream for zip file to read bytes of file
        FileOutputStream outter = new FileOutputStream(new File(folderw +"//"+ entry.toString())); //fileoutput stream creates file inside defined directory(folderw variable) by file's name
        outter.write(inpure.readAllBytes());// write into files which were created 
        outter.close();//closes fileoutput stream
    }

答案 3 :(得分:0)

你试过jUnrar吗?也许它可能有效: https://github.com/edmund-wagner/junrar

如果这也不起作用,我想你的存档在某种程度上已经损坏了。

答案 4 :(得分:0)

如果您知道将要运行此代码的环境,我认为您只需打电话给系统就可以为您解压缩它。它会比你在java中实现的任何东西都快。

我编写代码来提取带有嵌套目录的zip文件,它运行缓慢并耗费了大量CPU。我用这个代替了它:

    Runtime.getRuntime().exec(String.format("unzip %s -d %s", archive.getAbsolutePath(), basePath));

效果更好。

相关问题