2014-09-30 46 views
-3

我有代碼:CharsetDecoder不解碼數

byte[] str = new byte[17]; 

str[0] = 115; //s 
str[1] = 121; //y 
str[2] = 112; //p 
str[3] = 105; //i 
str[4] = 49; //current UnixTime numbers 
str[5] = 52; 
str[6] = 49; 
str[7] = 50; 
str[8] = 49; 
str[9] = 49; 
str[10] = 51; 
str[11] = 51; 
str[12] = 50; 
str[13] = 57; 
str[14] = 52; 
str[15] = 49; 
str[16] = 50; 


CharBuffer cb = CharBuffer.allocate(2048); 
ByteBuffer buf = ByteBuffer.wrap(str); 

Charset ch = Charset.forName("UTF-8"); 
CharsetDecoder cd = ch.newDecoder(); 
CoderResult cr = cd.decode(buf, cb, true); 
cb.flip(); 
System.out.println("!"+cb.toString()+"!"); 

但進入控制檯只有

sypi

  • 的System.out.println(bb.array ()。長度); // 17
  • 試過

    cd.onMalformedInput(CodingErrorAction.IGNORE); cd.onUnmappableCharacter(CodingErrorAction.IGNORE);

請原諒我的英語。

+0

您的代碼不會在那一刻編譯。你不應該在某個地方有一個CharBuffer嗎?理想情況下,發佈一個簡短但完整的程序來展示問題。 – 2014-09-30 21:57:37

+1

添加CharBuffer後適用於我。我猜想你的CharBuffer cb,無論你在哪裏聲明,都太小了。在這種情況下,你會得到'OVERFLOW'作爲CoderResult,這意味着需要再次調用charset轉換器來完成這項工作。 – Boann 2014-09-30 21:57:52

+1

爲什麼不只是'String test = new String(str,「UTF-8」);'?你想在這裏展示什麼? – markspace 2014-09-30 22:01:15

回答

0

該程序適用於我。它與修正後的例子基本相同。

public static void main(String[] args) 
      throws Exception 
    { 
     byte[] str = new byte[ 17 ]; 

     str[0] = 115; //s 
     str[1] = 121; //y 
     str[2] = 112; //p 
     str[3] = 105; //i 
     str[4] = 49; //current UnixTime numbers 
     str[5] = 52; 
     str[6] = 49; 
     str[7] = 50; 
     str[8] = 49; 
     str[9] = 49; 
     str[10] = 51; 
     str[11] = 51; 
     str[12] = 50; 
     str[13] = 57; 
     str[14] = 52; 
     str[15] = 49; 
     str[16] = 50; 

     String test = new String(str, "UTF-8"); 
     System.out.println(test); 

     ByteBuffer buf = ByteBuffer.wrap(str); 

     Charset ch = Charset.forName("UTF-8"); 
     CharsetDecoder cd = ch.newDecoder(); 
     CharBuffer cbuf = CharBuffer.allocate(1024); 
     CoderResult cr = cd.decode(buf, cbuf, true); 
     System.out.println("\"?"+cr+"?\""); 

     cbuf.flip(); 

     System.out.println("!" + cbuf.toString() + "!"); 
    } 

輸出:

run: 
sypi1412113329412 
"?UNDERFLOW?" 
!sypi1412113329412! 
BUILD SUCCESSFUL (total time: 2 seconds) 
+0

我只有這個工作: cb.clear(); – user2413972 2014-09-30 22:22:47