1

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
user1472672
  • 313
  • 1
  • 9
  • Does this answer your question? [Implementing in-memory compression for objects in Java](https://stackoverflow.com/questions/5934495/implementing-in-memory-compression-for-objects-in-java) – mdoflaz Jun 30 '22 at 11:15

1 Answers1

1

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.

f1sh
  • 11,489
  • 3
  • 25
  • 51