簡體   English   中英

Java代碼中的UTF-8問題

[英]UTF-8 issue in Java code

我得到的是字符串'Ðален½Ð'аÑÐ',而不是Java代碼中的'Календари'。 我如何將“Ðален½”和“Календари”轉換?

我用了

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

我相信您的代碼還可以。 看來您的問題是您需要進行特定的字符轉換,並且可能您的“真實”輸入未正確編碼。 為了進行測試,我將逐步進行標准的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);

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

  1. 俄語屏幕鍵盤 (懸停在Unicode值上)
  2. Unicode字符列表又如何呢?

編輯-
請注意,使用支持顯示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);
            }
        });
    }
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM