Moonie Asemani Moonie Asemani - 1 year ago 93
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 = != -1 ) {
} catch (Exception e){

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download