有没有一种方法可以在Java中将纯文本文件从字符串压缩成zip格式?

huangapple go评论74阅读模式
英文:

Is there a way to zip a plain text file from a String in java?

问题

我正在创建一个程序,用于创建一个包含各种内容的Zip文件。

现在,我想要添加一些自动生成的名为"info.txt"的文件,其中包含有关该Zip文件的信息。

我可能会将其生成为一个字符串,并希望将其放入Zip文件中。

不幸的是,我尚未找到任何这样做的方法,所以我真的很希望能得到一些帮助。

英文:

I am currently creating a program, that creates a Zip file of stuff.

Now, I would like to add some automatically generated "info.txt" file containing info about the Zip.

Now, I would probably just generate it as a String and would like to put it in the Zip.

Unfortunately, I have not found any way of doing this, so I would really appreciate some help.

答案1

得分: 1

琐碎。当你说,“我正在制作一个存放东西的压缩文件”时,我假设你正在使用`ZipOutputStream`,但如果不是的话,你应该更新你的问题。

```java
Path tgt = Paths.get("target.zip");
String info = "Hello, World!";
try (OutputStream out = Files.newOutputStream(tgt)) {
    ZipOutputStream zip = new ZipOutputStream(out);
    zip.putNextEntry(new ZipEntry("info.txt"));
    zip.write(info.getBytes(StandardCharsets.UTF_8));

    // 在这里写入其他文件
}
英文:

Trivial. When you say, "I am making a zip file of stuff", I assume you're using ZipOutputStream, but if not, you should update your question.

Path tgt = Paths.get("target.zip");
String info = "Hello, World!";
try (OutputStream out = Files.newOutputStream(tgt)) {
    ZipOutputStream zip = new ZipOutputStream(out);
    zip.putNextEntry(new ZipEntry("info.txt"));
    zip.write(info.getBytes(StandardCharsets.UTF_8));

    // write the other files here
}

huangapple
  • 本文由 发表于 2020年9月14日 21:28:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63885313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定