2

I tried to compress a string with DeflaterOutputStream and converted the output with base64 to save the result in another string

public static String compress(String str) throws IOException {
    byte[] data = str.getBytes("UTF-8");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    java.util.zip.Deflater compresser = new java.util.zip.Deflater(java.util.zip.Deflater.BEST_COMPRESSION, true);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, cozmpresser);
    deflaterOutputStream.write(data);
    deflaterOutputStream.close();
    byte[] output = stream.toByteArray();
    return Base64Coder.encodeLines(output);
}

Now i wish to try ZipOutputStream. i tried

public static String compress(String str) throws IOException {
    byte[] data = str.getBytes("UTF-8");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream deflaterOutputStream = new ZipOutputStream(stream);
    deflaterOutputStream.setMethod(ZipOutputStream.DEFLATED);
    deflaterOutputStream.setLevel(8);
    deflaterOutputStream.write(data);
    deflaterOutputStream.close();
    byte[] output = stream.toByteArray();
    return Base64Coder.encodeLines(output);
}

But dont work. ZipOutputStream seems orientated to a structure of folders and files how can I do?

Xavier Delamotte
  • 3,519
  • 19
  • 30
user1719863
  • 787
  • 1
  • 8
  • 13

1 Answers1

2

ZipOutputStream is intended to produce a Zip file, which, as you noticed, is generally used as a container for files and folders (a "compressed folder" or "compressed directory tree", in other words).

If you merely want to compress a string and then convert it to some printable form, ZipOutputStream isn't really the right choice. GZIPOutputStream is more appropriate to that purpose, in my opinion.

Since you marked this question with an android tag, note the comment here: http://developer.android.com/reference/java/util/zip/GZIPOutputStream.html

Using GZIPOutputStream is a little easier than ZipOutputStream because GZIP is only for compression, and is not a container for multiple files.

Brian Clapper
  • 25,705
  • 7
  • 65
  • 65
  • GZIPOutputStream seems goob but have no fast options. I'm trying to change compression using **OutputStream gzipout = new GZIPOutputStream(stream){{def.setLevel(java.util.zip.Deflater.BEST_COMPRESSION);}};** but I wish to remove headers too. Every Base64 string starts with H4sIAAAAAAAAA. There is a setting to avoid headers to be writted? – user1719863 Mar 27 '13 at 15:40