英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论