2012-04-02 65 views
4

我可以將字符串轉換爲數組爲UTF-8,但我無法將其轉換回字符串,如第一個字符串。Java,使用掃描儀輸入字符爲UTF-8,無法打印文本

public static void main(String[] args) { 

    Scanner h = new Scanner(System.in); 
    System.out.println("INPUT : "); 
    String stringToConvert = h.nextLine(); 
    byte[] theByteArray = stringToConvert.getBytes(); 

    System.out.println(theByteArray); 
    theByteArray.toString(); 
    String s = new String(theByteArray); 

    System.out.println(""+s); 
} 

如何將theByteArray作爲字符串打印?

+0

看起來像它的正常工作對我說:http://ideone.com/rcvXl – mellamokb 2012-04-02 17:23:29

+0

提供測試輸入/輸出預計/實際輸出。 – 2012-04-02 17:52:12

回答

12
String s = new String(theByteArray); 

確實應該

String s = new String(theByteArray, Charset.forName("UTF-8")); 

這裏的根本問題是String構造函數不聰明。 String構造函數不能區分正在使用的字符集,並會嘗試使用通常類似ASCII或ISO-8859-1的系統標準來轉換它。這就是爲什麼普通的A-Za-z看起來很正常,但其他一切都開始失敗。

字節是從-127到127運行的類型,因此UTF-8轉換連續字節需要連接在一起。 String構造函數不可能將它從字節數組中區分出來,因此默認情況下它將單獨處理每個字節(因此爲什麼基本字母數字在它們落入此範圍時總是可以工作)。

例子:

String text = "こんにちは"; 
byte[] array = text.getBytes("UTF-8"); 
String s = new String(array, Charset.forName("UTF-8")); 
System.out.println(s); // Prints as expected 
String sISO = new String(array, Charset.forName("ISO-8859-1")); // Prints 'ããã«ã¡ã¯' 
System.out.println(sISO); 
+0

+1我在自己的答案中錯過了Charset.forName(「UTF-8」) – 2012-04-09 18:40:15

2

有幾個問題,所提供的代碼:

  1. 你是不是保證你都可以從該字符串的UTF-8字節數組。

    byte[] theByteArray = stringToConvert.getBytes(); 
    

    返回與給定平臺上的默認編碼一個字節數組,如由JavaDoc說明。你真正想要做的是以下幾點:

    byte[] theByteArray = stringToConvert.getBytes("UTF-8"); 
    
  2. 您應該檢查documentationSystem.out.println()

    System.out.println(theByteArray); 
    

    呼籲System.out.println(Object x),這將打印x.toString()結果。默認情況下,toString()返回給定對象的內存地址。

    所以當你看到形式的輸出:

    輸入:

    [B @ 5f1121f6

    的inputText

    你們看到的是theByteArray的存儲位置然後是給定的文本輸入行。

  3. 您似乎不理解'x.toString()'方法。請記住,Java中的字符串是immutable;沒有一個字符串的方法會改變字符串。 theByteArray.toString();返回theByteArray;的字符串表示形式。返回的值是拋出,除非你給的值與另一個String

    String arrayAsString = theByteArray.toString(); 
    

    然而,如前所述,返回的字符串將是theByteArray的存儲位置。爲了打印出theByteArray的內容,你需要將其轉換爲字符串

    String convertedString = new String(theByteArray, Charset.forName("UTF-8")); 
    

假設您的要求打印轉換後的字符串,然後打印原始的字符串,你的代碼是這個樣子:

public static void main(String[] args) { 

    Scanner h = new Scanner(System.in); 
    System.out.println("INPUT : "); 
    String stringToConvert = h.nextLine(); 

    try { 
     // Array of the UTF-8 representation of the given String 
     byte[] theByteArray; 
     theByteArray = stringToConvert.getBytes("UTF-8"); 

     // The converted String 
     System.out.println(new String(theByteArray, Charset.forName("UTF-8"))); 
    } catch (UnsupportedEncodingException e) { 
     // We may provide an invalid character set 
     e.printStackTrace(); 
    } 

    // The original String 
    System.out.println(stringToConvert); 
} 
+0

非常感謝。你說很容易知道,但是這個代碼確實有效。比如我的示例輸入:Bác(基於越南語),轉換回String之後,我只看到方形.-' – famfamfam 2012-04-03 03:30:59

+0

你說得對。我用喬的回答糾正了我的錯誤。 – 2012-04-09 18:25:45