12
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
4

3 回答 3

14

尝试使用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
}
于 2013-09-27T07:08:32.563 回答
4

试试看:

//...

String string = "string";

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

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

//...
于 2013-09-27T07:20:34.203 回答
0

使用 FileOutputStream 保存字节

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

out.toString() 看起来很可疑,结果将是不可读的,如果您不在乎,那么为什么不返回 byte[],如果您在乎,它看起来会更好作为 hex 或 base64 字符串。

于 2013-09-27T07:24:54.757 回答