【发布时间】:2017-08-23 06:43:28
【问题描述】:
我已经搜索了很多从字节到字符串的转换,但我的查询有点不同,请继续阅读。
目前我有一个 gzip 文件,我可以使用http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/ 中的代码对其进行解压缩。 此代码帮助我将解压缩的输出存储在文件中,但如何将其存储在变量中?我目前正在使用此代码:
public String unGunzipFile(String compressedFile, String decompressedFile) {
byte[] buffer = new byte[1024];
try {
FileInputStream fileIn = new FileInputStream(compressedFile);
GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);
FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
StringBuffer str = new StringBuffer();
int bytes_read;
while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {
String s = new String(buffer);
str.append(s);
fileOutputStream.write(buffer, 0, bytes_read);
}
gZIPInputStream.close();
fileOutputStream.close();
System.out.println("The file was decompressed successfully!");
System.out.println(str);
String final_string = str.toString();
return final_string;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
由于当bytes_read 的长度不是 1024 时,我在末尾将字节转换为字符串,所以我最终在我的 StringBuffer 中得到了一些奇怪的数据,但是在文件中没有这样的数据,因为fileOutputStream.write(buffer, 0, bytes_read); 将其限制为写入更新的部分。
我该如何解决这个问题?
提前致谢。
【问题讨论】:
标签: java string byte gzipinputstream