在 Windows 中创建 Zip 文件并在 Linux 中解压 Zip 文件

2024-03-12

我在 Windows 下创建了一个 zip 文件(连同目录),如下所示(代码选自http://www.exampledepot.com/egs/java.util.zip/CreateZip.html http://www.exampledepot.com/egs/java.util.zip/CreateZip.html) :

package sandbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author yan-cheng.cheok
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // These are the files to include in the ZIP file
        String[] filenames = new String[]{"MyDirectory" + File.separator + "MyFile.txt"};

        // Create a buffer for reading the files
        byte[] buf = new byte[1024];

        try {
            // Create the ZIP file
            String outFilename = "outfile.zip";
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

            // Compress the files
            for (int i=0; i<filenames.length; i++) {
                FileInputStream in = new FileInputStream(filenames[i]);

                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(filenames[i]));

                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                // Complete the entry
                out.closeEntry();
                in.close();
            }

            // Complete the ZIP file
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

新创建的 zip 文件可以在 Windows 下毫无问题地解压,方法是使用http://www.exampledepot.com/egs/java.util.zip/GetZip.html http://www.exampledepot.com/egs/java.util.zip/GetZip.html

但是,我意识到如果我在 Linux 下提取新创建的 zip 文件,使用修改版本http://www.exampledepot.com/egs/java.util.zip/GetZip.html http://www.exampledepot.com/egs/java.util.zip/GetZip.html。原始版本不使用 zipEntry.isDirectory()) 检查目录。

public static boolean extractZipFile(File zipFilePath, boolean overwrite) {
    InputStream inputStream = null;
    ZipInputStream zipInputStream = null;
    boolean status = true;

    try {
        inputStream = new FileInputStream(zipFilePath);

        zipInputStream = new ZipInputStream(inputStream);
        final byte[] data = new byte[1024];

        while (true) {
            ZipEntry zipEntry = null;
            FileOutputStream outputStream = null;

            try {
                zipEntry = zipInputStream.getNextEntry();

                if (zipEntry == null) break;

                final String destination = Utils.getUserDataDirectory() + zipEntry.getName();

                if (overwrite == false) {
                    if (Utils.isFileOrDirectoryExist(destination)) continue;
                }

                if (zipEntry.isDirectory())
                {
                    Utils.createCompleteDirectoryHierarchyIfDoesNotExist(destination);
                }
                else
                {
                    final File file = new File(destination);
                    // Ensure directory is there before we write the file.
                    Utils.createCompleteDirectoryHierarchyIfDoesNotExist(file.getParentFile());

                    int size = zipInputStream.read(data);

                    if (size > 0) {
                        outputStream = new FileOutputStream(destination);

                        do {
                            outputStream.write(data, 0, size);
                            size = zipInputStream.read(data);
                        } while(size >= 0);
                    }
                }
            }
            catch (IOException exp) {
                log.error(null, exp);
                status = false;
                break;
            }
            finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    }
                    catch (IOException exp) {
                        log.error(null, exp);
                        break;
                    }
                }

                if (zipInputStream != null) {
                    try {
                        zipInputStream.closeEntry();
                    }
                    catch (IOException exp) {
                        log.error(null, exp);
                        break;
                    }
                }
            }

        }   // while(true)
    }
    catch (IOException exp) {
        log.error(null, exp);
        status = false;
    }
    finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.close();
            } catch (IOException ex) {
                log.error(null, ex);
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error(null, ex);
            }
        }
    }
    return status;
}

“MyDirectory\MyFile.txt”而不是 MyFile.txt 放置在文件夹 MyDirectory 下。

我尝试通过将 zip 文件创建代码更改为来解决该问题

    String[] filenames = new String[]{"MyDirectory" + "/" + "MyFile.txt"};

但是,通过硬编码分隔符,这是一个合格的解决方案吗?它可以在 Mac 操作系统下运行吗? (我没有 Mac 可以尝试)


是的,您的解决方案(尽管显然不优雅)是正确的方法。 “/”应该在 zipentry 内部使用,而不是本地 File.separator

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Windows 中创建 Zip 文件并在 Linux 中解压 Zip 文件 的相关文章

  • 使用 ProcessBuilder 运行 msys.bat

    我正在尝试使用 ProcessBuilder 在 java 中运行 msys bat 当我使用程序运行 bat 文件时 出现以下错误 找不到 rxvt exe 或 sh exe 二进制文件 正在中止 按任意键继续 这是代码 ProcessB
  • 如何通过无头活动处理静默 SEND 意图

    正如提问的用户所说 Android 上的默认浏览器如何发送 SEND 意图 https stackoverflow com questions 3320930 how does the default browser on android
  • Netbeans:如何从“设计”GUI 构建器向 JTable 添加 valueChanged 侦听器?

    我右键单击 JTable 并将一些代码插入到 后侦听器代码 中 结果很糟糕 我没有看到添加选项 table getSelectionModel addListSelectionListener new ListSelectionListen
  • Jprofiler Linux 上的远程分析。如何更改探查器数据文件的路径

    我正在 Linux 盒子上运行 java java 6 应用程序并进行其他设置 agentpath home myuser jprofiler bin linux x64 libjprofilerti so nowait 端口 7777 在
  • JFace DialogCellEditor:如何使按钮始终出现?

    我用的是JFaceDialogCellEditor在 JFace 的一行单元格中显示一个按钮TableViewer激活时会触发一个对话框 此行为适用于以下代码 但仅当显式选择托管按钮的表的单元格时才会显示该按钮 public class C
  • java中的内联初始化块

    我有课 public class MyMain public static void main String arg Temp t new Temp System out println instance initialize class
  • Eclipse 构建 Android 应用程序:如何在编译时创建两个版本?

    我正在编写一个 Android 应用程序 并希望基于相同的代码创建两个版本 免费版本和高级版本 我有两个版本的一个代码库 具有各种运行时检查来启用或禁用某些功能 例如 public class MyAppContext extends Ap
  • Spring中需要多个相同类型的bean

    将其标记为重复之前的请求 我浏览了论坛 但在任何地方都找不到该问题的解决方案 我正在使用 Spring 3 2 编写代码 一切都是纯粹基于注释的 该代码接收从不同 XSD 文件派生的 XML 文件 所以我们可以说 有五个不同的 XSD A1
  • Java,ASM:如何从ASM InsnNode获取操作码名称和TagValue?

    我正在研究一些类文件分析 并且正在研究使用 ASM 来读取类 在 Javap 中 操作码以及 tagName 和 tagValue 是内联打印的 但在每个 AbstractInsnNode 中 我只看到 int 的字段 而不是 tagVal
  • JTable 中的格式化字段问题 - Integer 和 Double 之间的差异

    更新 已确认为错误当 columnClass 为 Double 时 JTable 无法将给定对象格式化为 Number 错误 ID 7051636 https bugs java com bugdatabase view bug bug i
  • 通过 jdbc 执行存储过程时获取网关超时

    我正在使用 struts2 框架 它基本上是这样的 ActionClass execute call function in business class which returns an object and store this obj
  • mapFragment.getMapAsync 处的 NullPointerException

    在解决了与我的标题相关的问题后 我找不到问题的解决方案 我有一个NullPointerException at mapFragment getMapAsync 下面是我的MapActivity code package com exampl
  • LDAP中超时的实现

    我一直在处理我们正在使用的应用程序LDAP获取用户详细信息 有时获取用户详细信息需要更多时间 我想实施time out获取详细信息的方法 以便我们可以避免在最坏的情况下在服务器中挂起事务 这里我们使用的是LdapUtil我们在其中配置的类L
  • Spring数据异常处理

    我正在使用 Spring Data JPA 开发一个项目 我需要处理 JpaRepository 方法调用中的一些异常 在下面的代码中 我需要拦截主键违规错误 但无法直接捕获异常 就我而言 当发生此类异常时 存储库层 JpaReposito
  • java SWT透明复合背景

    我有复合对象 Composite composite new Composite shell SWT NONE composite setBounds new Rectangle 10 10 100 100 我如何使这个组合具有透明背景 我
  • 光线追踪三角形

    我正在用java编写一个光线追踪器 并且我能够追踪球体 但我相信我追踪三角形的方式有问题 据我了解 这是基本算法 首先确定射线是否与plane三角形已打开 剪裁所有点 使它们与三角形位于同一平面上 因此xy以平面为例 根据沿着新平面向任意方
  • 可以将矩形设置为显示边框吗?

    以下应用 public class Temp extends Application Override public void start Stage primaryStage StackPane root new StackPane Re
  • JDBC多线程插入可以吗?

    我目前正在开发一个 Java 项目 我需要准备一个大的 对我来说 mysql 数据库 我必须使用 Jsoup 进行网页抓取并将结果存储到我的数据库中 据我估计 我将大约插入 1 500 000 到 2 000 000 条记录 在我的第一次试
  • Java - 全局、可重用的加载对话框

    我正在尝试实现一个全局加载对话框 我想调用一些静态函数来显示对话框和一些静态函数来关闭它 与此同时 我正在主线程或子线程中做一些工作 我尝试以下操作 但对话框没有更新 最后一次 在再次隐藏之前 它会更新 private static Run
  • Java 压缩字符串

    我需要创建一个接收字符串并返回字符串的方法 防爆输入 AAABBBCCC 防爆输出 3A4B2C 好吧 这很尴尬 我在今天的面试中无法做到这一点 我正在申请初级职位 现在 我在家尝试制作一些静态工作的东西 我的意思是 不使用循环有点无用 但

随机推荐