混合
String和
byte[];
那永远不适合。并且仅适用于具有相同编码的相同OS。并非每个
byte[]都可以转换为
String,并且转换回可以提供其他字节。
在
compressedBytes需求不能代表一个字符串。
在
getBytes和中明确设置编码
new String。
String orig = "............."; // Compress it ByteArrayOutputStream baostream = new ByteArrayOutputStream(); OutputStream outStream = new GZIPOutputStream(baostream); outStream.write(orig.getBytes("UTF-8")); outStream.close(); byte[] compressedBytes = baostream.toByteArray(); // toString not always possible // Uncompress it InputStream inStream = new GZIPInputStream( new ByteArrayInputStream(compressedBytes)); ByteArrayOutputStream baoStream2 = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len; while ((len = inStream.read(buffer)) > 0) { baoStream2.write(buffer, 0, len); } String uncompressedStr = baoStream2.toString("UTF-8"); System.out.println("orig: " + orig); System.out.println("unc: " + uncompressedStr);


