【问题标题】:Java.util.zip adding a new file overwrites entire jar?Java.util.zip 添加一个新文件会覆盖整个 jar?
【发布时间】:2013-07-06 07:42:21
【问题描述】:

我正在使用 java.util.zip 将一些配置资源添加到 jar 文件中。 当我调用 addFileToZip() 方法时,它会完全覆盖 jar,而不是将文件添加到 jar 中。为什么我需要将配置写入 jar 完全无关紧要。而且我不希望使用任何外部 API。

编辑:jar 未在 VM 中运行,org.cfg.resource 是我试图将文件保存到的包,该文件是标准文本文档,并且正在编辑的 jar 包含在此之前的正确信息使用方法。

我的代码:

public void addFileToZip(File fileToAdd, File zipFile)
{
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    ZipEntry ze = null;
    byte[] buffer = null;
    int len;

    try {
        zos = new ZipOutputStream(new FileOutputStream(zipFile));
    } catch (FileNotFoundException e) {
    }

    ze = new ZipEntry("org" + File.separator + "cfg" + 
            File.separator + "resource" + File.separator + fileToAdd.getName());
    try {
        zos.putNextEntry(ze);

        fis = new FileInputStream(fileToAdd);
        buffer = new byte[(int) fileToAdd.length()];

        while((len = fis.read(buffer)) > 0)
        {
            zos.write(buffer, 0, len);
        }           
    } catch (IOException e) {
    }
    try {
        zos.flush();
        zos.close();
        fis.close();
    } catch (IOException e) {
    }
}

【问题讨论】:

  • 它是重复的,但是 3 年前提出的另一个问题的答案没有提到 zip 文件系统。 Zip 文件系统最早出现在 Java 7 中。

标签: java configuration jar zip


【解决方案1】:

您显示的代码会覆盖文件,无论它是否是 zip 文件。 ZipOutputStream 不关心现有数据。任何面向流的 API 都没有。

我会推荐

  1. 使用ZipOutputStream 创建新文件。

  2. ZipInputStream打开现有的

  3. 将现有条目复制到新文件。

  4. 添加新条目。

  5. 用新文件替换旧文件。


希望在 Java 7 中我们得到了Zip File System,这将为您节省大量工作。

我们可以直接写入zip文件里面的文件

Map<String, String> env = new HashMap<>(); 
env.put("create", "true");
Path path = Paths.get("test.zip");
URI uri = URI.create("jar:" + path.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, env))
{
    Path nf = fs.getPath("new.txt");
    try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
        writer.write("hello");
    }
}

【讨论】:

  • 好的,明天我会试一试,我会回复你的进展情况,听起来它会起作用,感谢你的帮助。 +1 获取信息和可能的修复。
  • @user1718720 再次检查答案,我添加了Zip文件系统,这将为您节省大量工作。
  • 为此文件是否必须存在于 zip 中?提前加空格没问题,重点是改文件内容。
  • @user1718720 如果文件不存在,此示例将创建文件。这要感谢StandardOpenOption.CREATE。查看其他选项以获得您需要的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 2012-08-13
相关资源
最近更新 更多