有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

这里我有一个文件夹(ZipFilesFolder),它由10个zip文件组成,比如说一个。齐普,两个。齐普,三个。拉链十zip,我每次都会将文件作为zipFilename从这个文件夹传递到zipFileToUnzip。我需要在同一个文件夹(ZipFilesFolder)中得到结果,我需要解压这些文件,而不是一个。齐普,两个。拉链一、二、三文件夹必须可见

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) 个答案

  1. # 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