Pergunta

public static String compressString(String str) throws IOException{
    if (str == null || str.length() == 0) {
        return str;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    Gdx.files.local("gziptest.gzip").writeString(out.toString(), false);
    return out.toString();
}

When I save that string to a file, and run gunzip -d file.txt in unix, it complains:

gzip: gzip.gz: not in gzip format
Foi útil?

Solução

Try to use BufferedWriter

public static String compressString(String str) throws IOException{
if (str == null || str.length() == 0) {
    return str;
}

BufferedWriter writer = null;

try{
    File file =  new File("your.gzip")
    GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(file));

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

    writer.append(str);
}
finally{           
    if(writer != null){
     writer.close();
     }
  }
 }

About your code example try:

public static String compressString(String str) throws IOException{
if (str == null || str.length() == 0) {
    return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();

byte[] compressedBytes = out.toByteArray(); 

Gdx.files.local("gziptest.gzip").writeBytes(compressedBytes, false);
out.close();

return out.toString(); // I would return compressedBytes instead String
}

Outras dicas

Try that :

//...

String string = "string";

FileOutputStream fos = new FileOutputStream("filename.zip");

GZIPOutputStream gzos = new GZIPOutputStream(fos);
gzos.write(string.getBytes());
gzos.finish();

//...

Save bytes from out with FileOutputStream

FileOutputStream fos = new FileOutputStream("gziptest.gz");
fos.write(out.toByteArray());
fos.close();

out.toString() seems suspicious, the result will be unreadable, if you dont care then why not to return byte[], if you do care it would look better as hex or base64 string.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top