Сжать строку в gzip в Java

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();
}

Когда я сохраняю эту строку в файл и запускаю gunzip -d file.txt в unix жалуется:

gzip: gzip.gz: not in gzip format

3 ответа

Решение

Попробуй использовать 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();
     }
  }
 }

О вашем примере кода попробуйте:

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
}

Попробуй это:

//...

String string = "string";

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

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

//...

Сохранить байты из с помощью FileOutputStream

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

out.toString () кажется подозрительным, результат будет нечитаемым, если вам все равно, почему бы не вернуть byte[], если вам все равно, он будет выглядеть лучше в виде строки hex или base64.

Другие вопросы по тегам