How to preserve the source file when compressing with Gzip in Java?

In Java, you can use GZIPOutputStream to perform gzip compression, but you cannot directly retain the original file because the compression operation processes the data and outputs it to a target file. If you want to retain the original file, you can first read the content of the source file into memory, then perform the compression operation, and finally write the compressed data to the target file and write the original file content back to the source file.

Here is a simple sample code demonstrating how to compress using gzip and keep the original file.

import java.io.*;
import java.util.zip.GZIPOutputStream;

public class GzipExample {

    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String targetFile = "target.gz";

        try {
            // 读取源文件内容
            FileInputStream fis = new FileInputStream(sourceFile);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

            // 压缩源文件内容
            FileOutputStream fos = new FileOutputStream(targetFile);
            GZIPOutputStream gos = new GZIPOutputStream(fos);
            gos.write(baos.toByteArray());
            gos.close();

            // 将源文件内容写回源文件
            FileOutputStream fos2 = new FileOutputStream(sourceFile);
            fos2.write(baos.toByteArray());

            fis.close();
            baos.close();
            fos.close();
            fos2.close();
            
            System.out.println("压缩并保留源文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, the source file content is first read into memory, then compressed using GZIPOutputStream, and the compressed data is written to the target file. Finally, the source file content is written back to the source file, completing the compression while preserving the original file.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds