英文:
How do you append to the end of a gzipped file in Java?
问题
以下是您提供的代码的中文翻译:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression {
public static void main(String[] args) throws IOException {
File file = new File("gziptest.zip");
try (OutputStream os = new GZIPOutputStream(new FileOutputStream(file, true))) {
os.write("test".getBytes());
}
try (GZIPInputStream inStream = new GZIPInputStream(new FileInputStream(file))) {
while (inStream.available() > 0) {
System.out.print((char) inStream.read());
}
}
}
}
根据我所了解,根据您的描述,这段代码应该将 "test" 添加到 "gziptest.zip" 文件的末尾。但是,当运行代码时,文件没有被修改。奇怪的是,如果将 FileOutputStream(file, true)
更改为 FileOutputStream(file, false)
,则文件确实会被修改,但它的原始内容会被覆盖,这显然不是您想要的结果。
我使用的是JDK 14.0.1。
英文:
Here is what I've tried
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression {
public static void main(String[] args) throws IOException {
File file = new File("gziptest.zip");
try ( OutputStream os = new GZIPOutputStream(new FileOutputStream(file, true))) {
os.write("test".getBytes());
}
try ( GZIPInputStream inStream = new GZIPInputStream(new FileInputStream(file))) {
while (inStream.available() > 0) {
System.out.print((char) inStream.read());
}
}
}
}
Based on what I've read, this should append "test" to the end of gziptest.zip, but when I run the code, the file doesn't get modified at all. The strange thing is that if I change FileOutputStream(file, true)
to FileOutputStream(file, false)
, the file does get modified, but its original contents are overriden which is of course not what I want.
I am using JDK 14.0.1.
答案1
得分: 3
- Zip 和 GZip 是不同的。如果你要进行 GZip 测试,你的文件应该使用 .gz 扩展名,而不是 .zip。
- 要正确地将 "test" 附加到 GZip 数据的末尾,你应该首先使用 GZIPInputStream 从文件中读取,然后将 "test" 附加到未压缩的文本上,最后通过 GZipOutputStream 发送回去。
英文:
A couple of things here.
- Zip and GZip are different.. If you are doing a gzip test, your file should have the extension .gz, not .zip
- To properly append "test" to the end of the gzip data, you should first use a GZIPInputStream to read in from the file, then tack "test" onto the uncompressed text, and then send it back out through GZipOutputStream
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论