gpt4 book ai didi

Java.util.zip 添加新文件会覆盖整个 jar 吗?

转载 作者:行者123 更新时间:2023-12-04 04:50:39 27 4
gpt4 key购买 nike

我正在使用 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) {
}
}

最佳答案

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

我会推荐

  1. 使用 ZipOutputStream 创建新文件。

  2. 打开现有的 ZipInputStream

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

  4. 添加新条目。

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


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

我们可以直接写入压缩文件中的文件

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");
}
}

关于Java.util.zip 添加新文件会覆盖整个 jar 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17500856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com