我需要将一个字符串保存到文件中,我使用DeflaterOutputStream进行压缩。但是当我尝试解压缩时,无法得到原始字符串。我得到了一些未清除的符号。 以下是我的代码:
public static void decompress() throws Exception {
InputStream in=new FileInputStream("E:/codes.txt");
InflaterInputStream ini = new InflaterInputStream(in);
ByteArrayOutputStream bout =new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
ini.close();
bout.close();
String s=new String(bout.toByteArray());
System.out.print(s);
}
public static void compressData(byte[] data) throws Exception {
OutputStream out=new FileOutputStream("E:/test.txt");
Deflater d = new Deflater();
DeflaterOutputStream dout = new DeflaterOutputStream(out, d);
dout.write(data);
dout.close();
}
public static void main(String[] args) throws Exception {
compressData("My name is Motasem".getBytes());
decompress();
}
我不确定问题出在哪里。我原以为是将字节数组转换成字符串时出了问题,但我尝试过这个方法,它是有效的。您可以查看这个网站:http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/