gpt4 book ai didi

java - 在 Java 中将字符串压缩为 gzip

转载 作者:搜寻专家 更新时间:2023-10-30 21:24:05 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 在 Java 中将字符串压缩为 gzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19044638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com