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();
}
Run Code Online (Sandbox Code Playgroud)
当我将该字符串保存到文件并gunzip -d file.txt在unix中运行时,它会抱怨:
gzip: gzip.gz: not in gzip format
Run Code Online (Sandbox Code Playgroud)
Max*_*tin 13
尝试使用 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
关于你的代码示例尝试:
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
}
Run Code Online (Sandbox Code Playgroud)