2011-12-23 36 views
2

我得到一個字符串'ÐалÐμнÐ'аÑÐ',而不是在Java代碼中獲得'Календари'。我怎樣才能把'алÐμнÐ'аÑÐ'換成'Календари'?Java代碼中的UTF-8問題

我用

String convert =new String(convert.getBytes("iso-8859-1"), "UTF-8") 
String convert =new String(convert.getBytes(), "UTF-8") 
+3

你能擴展的代碼示例一點點?它不清楚輸入來自哪裏。還不清楚,如果你正在閱讀io,或者在內存中有字符串? – Bill 2011-12-23 05:43:07

+0

第一行適用於我的代碼 – 2011-12-23 05:47:14

+0

字符串從哪裏開始?你爲什麼使用ISO-8859-1,它不能對你顯示的字符進行編碼? – deceze 2011-12-23 05:59:38

回答

4

我相信你的代碼是好的。看來你的問題是你需要做一個特定的字符轉換,也許你的「真實」的輸入沒有被正確編碼。爲了測試,我會做一個標準的逐步CharSet編碼/解碼,以查看事情正在破裂的地方。

您的編碼看起來很好,http://docs.oracle.com/javase/1.6/docs/guide/intl/encoding.doc.html

而下面似乎正常運行:

//i suspect your problem is here - make sure your encoding the string correctly from the byte/char stream. That is, make sure that you want "iso-8859-1" as your input characters. 

Charset charsetE = Charset.forName("iso-8859-1"); 
CharsetEncoder encoder = charsetE.newEncoder(); 

//i believe from here to the end will probably stay the same, as per your posted example. 
Charset charsetD = Charset.forName("UTF-8"); 
CharsetDecoder decoder = charsetD.newDecoder(); 

ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(inputString)); 
CharBuffer cbuf = decoder.decode(bbuf); 
final String result = cbuf.toString(); 
System.out.println(result); 
+2

是的,我也試過這個代碼也..在Eclipse中工作。同時,當我在NetBeans中運行此代碼生成的字符串看起來像這樣'???????' – chinchu 2011-12-23 06:13:06

+0

這可能是一個jdk問題或輸入問題....?用charset.isEncodngSupported檢查 – jayunit100 2011-12-23 12:48:38

2

使用Unicode值,而不是字符串文字。欲瞭解更多信息,請參見:

  1. Russian on-screen keyboard(將鼠標懸停在爲Unicode值)
  2. 又有怎樣的一個list of Unicode characters

編輯 -
。注意,使用支持顯示Unicode值輸出的字體(例如Arial Unicode MS)是很重要的。

示例 -

import java.awt.FlowLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

final class RussianDisplayDemo extends JFrame 
{ 
    private static final long serialVersionUID = -3843706833781023204L; 

    /** 
    * Constructs a frame the is initially invisible to display Russian text 
    */ 
    RussianDisplayDemo() 
    { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     getContentPane().setLayout(new FlowLayout()); 
     add(getRussianButton()); 
     setLocationRelativeTo(null); 
     pack(); 
    } 

    /** 
    * Returns a button with Russian text 
    * 
    * @return a button with Russian text 
    */ 
    private final JButton getRussianButton() 
    { 
     final JButton button = new JButton("\u042da\u043d\u044f\u0442\u043e"); // Russian for "Busy" 
     return button; 
    } 

    public static final void main(final String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public final void run() 
      { 
       final RussianDisplayDemo demo = new RussianDisplayDemo(); 
       demo.setVisible(true); 
      } 
     }); 
    } 
} 

enter image description here