在Java中将字符串压缩为gzip

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

当我将该字符串保存到文件中,并在Unix中运行gunzip -d file.txt时,它会报错:

gzip: gzip.gz: not in gzip format

为什么不直接使用FileOutputStream(而不是ByteArrayOutputStream)?你试过那样做会发生什么吗? - Sven Amann
这是libgdx,它是一个跨平台的游戏开发库。我只是将其写入文件以进行故障排除。实际上,我一直在尝试通过http POST请求将字符串发送到我的flask服务器,但服务器端抱怨该字符串不是有效的gzip格式。 - kelorek
我猜问题出在你将压缩数据转换为字符串的过程中。我认为你应该将结果视为byte[]。libgdx能否将byte[]写入文件? - Sven Amann
可以。尝试使用Gdx.files.local("gziptest.gzip").writeBytes(out.getBytes(), false)。会发生什么? - Sven Amann
3个回答

15

尝试使用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
}

这会生成一个有效的gzip对象。但我真正想要的是返回一个字符串。我能绕过写文件吗? - kelorek
针对您的示例,请先尝试以下代码:ByteArrayOutputStream out = new ByteArrayOutputStream(str.length()); - Maxim Shoustin
看一下我上面发布的修改,我稍微改了你的代码。 - Maxim Shoustin
可以。但是最终我需要将其转换为字符串并发送到我的Flask应用程序中 - 你为什么建议返回byte[] - kelorek
因为它是不可读的字符串,我认为,我不知道你想在那之后做什么。如果你发送 byte[],你可以在之后解压缩它。 - Maxim Shoustin
显示剩余2条评论

4

请尝试以下操作:

//...

String string = "string";

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

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

//...

0

使用 FileOutputStream 将字节保存到输出流中

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

out.toString() 看起来有点可疑,结果可能无法读取。如果您不关心结果,则为什么不返回 byte[] 呢?如果您关心结果,将其转换为十六进制或 base64 字符串会更好。


同意,我会从out.toByteArray()返回byte[] - Maxim Shoustin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接