user1472672
user1472672

Reputation: 365

How to create a GZIP file in Java from another file without creating a new physical file

I was working with this example:

public class GZipExample {

    public static void main(String[] args) {

        // compress a file
        Path source = Paths.get("/home/test/sitemap.xml");
        Path target = Paths.get("/home/test/sitemap.xml.gz");

        if (Files.notExists(source)) {
            System.err.printf("The path %s doesn't exist!", source);
            return;
        }

        try {

            GZipExample.compressGzip(source, target);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // copy file (FileInputStream) to GZIPOutputStream
    public static void compressGzip(Path source, Path target) throws IOException {

        try (GZIPOutputStream gos = new GZIPOutputStream(
                                      new FileOutputStream(target.toFile()));
             FileInputStream fis = new FileInputStream(source.toFile())) {

            // copy file
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                gos.write(buffer, 0, len);
            }

        }

    }

I would like only to create the gzip file in memory and not physically on disk. I'm not sure if that is possible using some kind of stream or in-memory file?

Upvotes: 1

Views: 1183

Answers (1)

f1sh
f1sh

Reputation: 11934

You can write to any OutputStream you want, meaning that it does not need to be a FileOutputStream. You can use a ByteArrayOutputStream instead:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gos = new GZIPOutputStream(baos);
     FileInputStream fis = new FileInputStream(source.toFile())) {

        // copy file
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) > 0) {
            gos.write(buffer, 0, len);
        }
}
byte[] data = baos.toByteArray();

The gzipped data is now a byte[] in your memory.

Upvotes: 1

Related Questions