2009-05-09 39 views

回答

2

看起来像一个字符的编码/解码问题给我。应该使用Readers/Writers来编写字符串,例如String.getBytes()。使用String(new byte[])结构是适当方式..

你真的应该使用一个循环来读取和检查返回字节读取值,确保一切读回!

1

我建议你使用gCompress.close()not finish();

我也建议你不能依赖str.length()足够长的时间去阅读。数据可能会更长,所以字符串会被截断。

您也忽略read()的返回值。 read()只保证读取()一个字节,不可能完全读取str.length()字节的数据,因此您可能会有很多尾随nul个字节\ 0。相反,你可以期望读str.getBytes()长()

+0

几乎每一行都有一个错误 - 我是一个完美的例子,说明如何*不*达到最终目标。 – 2009-05-09 10:07:09

5

重申一下其他人所说:

  • 这是通常的情况是str.length()= str.getBytes(! ).length()。许多操作系统使用可变长度编码(如UTF-8, UTF-16 or Windows-949)。使用OutputStream.close方法确保所有数据都被正确写入。
  • 使用InputStream.read的返回值来查看已读取多少个字节。无法保证所有数据都能一次读取。
  • Be careful使用String类进行编码/解码时。

字符串压缩/解压缩方法

private static byte[] compress(String str, Charset charset) { 
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    try { 
     OutputStream deflater = new GZIPOutputStream(buffer); 
     deflater.write(str.getBytes(charset)); 
     deflater.close(); 
    } catch (IOException e) { 
     throw new IllegalStateException(e); 
    } 
    return buffer.toByteArray(); 
    } 

    private static String decompress(byte[] data, 
     Charset charset) { 
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    ByteArrayInputStream in = new ByteArrayInputStream(data); 
    try { 
     InputStream inflater = new GZIPInputStream(in); 
     byte[] bbuf = new byte[256]; 
     while (true) { 
     int r = inflater.read(bbuf); 
     if (r < 0) { 
      break; 
     } 
     buffer.write(bbuf, 0, r); 
     } 
    } catch (IOException e) { 
     throw new IllegalStateException(e); 
    } 
    return new String(buffer.toByteArray(), charset); 
    } 

    public static void main(String[] args) throws IOException { 
    StringBuilder sb = new StringBuilder(); 
    while (sb.length() < 10000) { 
     sb.append("write the data here \u00A3"); 
    } 
    String str = sb.toString(); 
    Charset utf8 = Charset.forName("UTF-8"); 
    byte[] compressed = compress(str, utf8); 

    System.out.println("String len=" + str.length()); 
    System.out.println("Encoded len=" 
     + str.getBytes(utf8).length); 
    System.out.println("Compressed len=" 
     + compressed.length); 

    String decompressed = decompress(compressed, utf8); 
    System.out.println(decompressed.equals(str)); 
    } 

(请注意,因为这些都是在内存中的数据流,我不being strict我如何打开或关闭它们。)