zip文件不是在同一个文件夹中解压缩?

时间:2014-05-30 09:13:11

标签: java file zip unzip

这里我有文件夹(ZipFilesFolder),它包含10个zip文件,例如one.zip,two.zip,three.zip..ten.zip,我每次都会从这个文件夹传递文件到zipFileToUnzip作为zipFilename.I需要在同一文件夹(ZipFilesFolder)中的结果我需要解压缩那些文件而不是one.zip,two.zip,..一,二,三文件夹必须可见。

public static void zipFileToUnzip(File zipFilename) throws IOException {
    try {
        //String destinationname = "D:\\XYZ";
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(new FileInputStream(zipFilename));

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = zipentry.getName();
            System.out.println("entryname " + entryName);
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(entryName);
            String directory = newFile.getParent();

            if (directory == null) {
                if (newFile.isDirectory()) {
                    break;
                }
            }
            fileoutputstream = new FileOutputStream(
                    destinationname + entryName);
            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }
            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }//while
        zipinputstream.close();
    } catch (IOException e) {
    }
}

这是我的代码,但它不起作用,任何人都可以帮助我,如何获得所需的输出。

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 自评论destinationname以来未编译,但在打开FileOutputStream
  • 时引用
  • IOException被捕获并被忽略。如果您抛出它们,您将收到可以帮助您诊断问题的错误消息
  • 打开FileOutputStream时,只需连接两个字符串而不在其间添加路径分隔符。
  • 如果要创建的文件位于目录中,则不会创建该目录,因此FileOutputStream无法创建该文件。
  • 发生异常时,
  • 流不会关闭。

如果您不介意使用guava,这简化了将流复制到文件的生活,您可以使用此代码:

public static void unzipFile(File zipFile) throws IOException {
    File destDir = new File(zipFile.getParentFile(), Files.getNameWithoutExtension(zipFile.getName()));
    try(ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipFile))) {
        ZipEntry zipEntry = zipStream.getNextEntry();
        if(zipEntry == null) throw new IOException("Empty or no zip-file");
        while(zipEntry != null) {
            File destination = new File(destDir, zipEntry.getName());
            if(zipEntry.isDirectory()) {
                destination.mkdirs();
            } else {
                destination.getParentFile().mkdirs();
                Files.asByteSink(destination).writeFrom(zipStream);
            }
            zipEntry = zipStream.getNextEntry();
        }
    }
}

或者您也可以使用zip4j,另请参阅此question