在 Java 中将字符串压缩为 gzip

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19044638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:37:52  来源:igfitidea点击:

Compress a string to gzip in Java

javagzipgunzip

提问by kelorek

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.txtin unix, it complains:

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

gzip: gzip.gz: not in gzip format

采纳答案by Maxim Shoustin

Try to use BufferedWriter

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

回答by Maxim Shoustin

Try that :

试试看:

//...

String string = "string";

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

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

//...

回答by Evgeniy Dorofeev

Save bytes from out with FileOutputStream

使用 FileOutputStream 从 out 中保存字节

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.

out.toString() 看起来很可疑,结果将是不可读的,如果你不关心那么为什么不返回 byte[],如果你关心它会更好看作为十六进制或 base64 字符串。