【发布时间】:2026-01-26 12:20:06
【问题描述】:
我正在使用 GZIPOutputStream 将一个 xml 文件压缩为 gz 文件,但压缩后我发现 gz 文件层次结构中缺少 xml 文件的扩展名 (.xml)。我需要保留扩展名,因为第三方系统将使用压缩的 gz 文件,该系统期望在解压缩 gz 文件后获得一个 .xml 文件。有什么解决方案吗?我的测试代码是:
public static void main(String[] args) {
compress("D://test.xml", "D://test.gz");
}
private static boolean compress(String inputFileName, String targetFileName){
boolean compressResult=true;
int BUFFER = 1024*4;
byte[] B_ARRAY = new byte[BUFFER];
FileInputStream fins=null;
FileOutputStream fout=null;
GZIPOutputStream zout=null;
try{
File srcFile=new File(inputFileName);
fins=new FileInputStream (srcFile);
File tatgetFile=new File(targetFileName);
fout = new FileOutputStream(tatgetFile);
zout = new GZIPOutputStream(fout);
int number = 0;
while((number = fins.read(B_ARRAY, 0, BUFFER)) != -1){
zout.write(B_ARRAY, 0, number);
}
}catch(Exception e){
e.printStackTrace();
compressResult=false;
}finally{
try {
zout.close();
fout.close();
fins.close();
} catch (IOException e) {
e.printStackTrace();
compressResult=false;
}
}
return compressResult;
}
【问题讨论】:
-
GZipOutputStream 不关心文件,它只是压缩你扔给它的字节。您保存该流的文件名应该是您在
targetFileName中设置的任何内容。 -
是的,运行这段代码后,我们可以得到一个名为“test.gz”的文件,如果我们使用诸如WinRAR之类的zip工具查看这个文件,我们可以看到一个名为作为其中的“测试”(不是“test.xml”);如果我们直接解压“test.gz”,我们会得到一个文件“test”而不是“test.xml”,这就是我提到的问题。
-
是的,这正是您需要将压缩文件命名为
test.xml.gz的原因 - 在 Unix/Linux 系统上尝试一下。如果你去掉文件扩展名并用“gz”替换它,你当然会丢失扩展名。