如何 gzip 文件就地替换 Java
How to gzip file in place replacement Java
我有一个 .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 文件就地替换未压缩的文件?
成功压缩并写入 gzip 文件后,只需对原始文件使用 File.delete()
。
您必须非常小心,在确定新的压缩文件已成功写入并关闭之前,不要删除原始文件。否则您将自己设置为丢失数据。
我有一个 .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 文件就地替换未压缩的文件?
成功压缩并写入 gzip 文件后,只需对原始文件使用 File.delete()
。
您必须非常小心,在确定新的压缩文件已成功写入并关闭之前,不要删除原始文件。否则您将自己设置为丢失数据。