我有一个.xlsx文件(或任何文件),我想gzip。我能够gzip文件,但现在我有尝试这样做的问题。意味着用文件的gzip压缩版本替换原始文件。
这是我的代码:
public static void main(String[] args) throws IOException {
File file = new File("test.xlsx");
File gfile = new File(file.getAbsolutePath()+".gz");
if(!file.exists()) {
System.err.println("Input tax file did not exist!");
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(gfile);
GZIPOutputStream gos = new GZIPOutputStream(fos);
gzipReplace(fis, gos);
}
private static void gzipReplace(InputStream is, OutputStream os) {
int oneByte;
try {
while( (oneByte = is.read()) != -1 ) {
os.write(oneByte);
}
os.close();
is.close();
} catch (Exception e){
System.err.println(e.getStackTrace());
}
}
如何使用gzip压缩文件就地替换未压缩文件?
答案 0 :(得分:1)
在成功压缩和编写gzip文件后,只需在原始文件上使用File.delete()
。
在确定新压缩文件已成功写入和关闭之前,您必须非常小心不要删除原始文件。否则你就是在设置自己的数据。