Moonie Asemani Moonie Asemani - 26 days ago 12
Apache Configuration Question

How to gzip file in place replacement Java

I have a .xlsx file (or any file) which I would like to gzip. I am able to gzip the file but now I have the problem of trying to do this in place. Meaning to replace the original file with the gzipped version of the file.

Here is my code:

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());
}
}


How can I do an in-place replacement of an uncompressed file with a gzipped one?

Answer

Just use File.delete() on the original file after successful compression and writing of the gzip file.

You must be very careful to not delete the original file until you are certain that the new compressed file was successfully written and closed. Otherwise you are setting yourself up to lose data.