String to GZIPOutputStream

23.1k views Asked by At

I've tried searching and couldn't find anything. What I'm trying to do is I'm looping through a list where I'm constructing a string from a combination of items from multiple lists. I then want to dump these strings to a gzipped file. I got it working with just dumping it to a plain ascii text file but I can't seem to get it to work with the gzipoutputstream. So basically,

Loop create string dump string to gzipped file endloop

If possible, I'd like to avoid dumping to a plain text file then gzipping it since these files will be almost 100 meg each.

2

There are 2 answers

0
Malcolm Smith On BEST ANSWER

Yes, you can do this no problem. You just need to use a writer to convert from your character based strings to the byte based gzip stream.

    BufferedWriter writer = null;
    try {
        GZIPOutputStream zip = new GZIPOutputStream(
            new FileOutputStream(new File("tmp.zip")));

        writer = new BufferedWriter(
            new OutputStreamWriter(zip, "UTF-8"));

        String[] data = new String[] { "this", "is", "some", 
            "data", "in", "a", "list" };

        for (String line : data) {
            writer.append(line);
            writer.newLine();
        }
    } finally {         
        if (writer != null)
            writer.close();
    }

Also, remember gzip just compresses a stream, if you want embeded files, see this post: gzip archive with multiple files inside

0
kissLife On
try {
        String srcString = "the string you want to zip.";

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(stream);
        gzip.write(srcString.getBytes(StandardCharsets.UTF_8));
        gzip.close();

        // the gzip bytes you get
        byte[] zipBytes = stream.toByteArray();

    } catch (IOException ex) {
        // ...
    }