繁体   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