2009-05-09 44 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我如何打開或關閉它們。)