我得到一个字符串'ÐалÐμнÐ'аÑÐ'而不是在Java代码中获取'Календари'。如何将'ÐалÐμнÐ'аÑÐ'转换为'Календари'?
我用过
String convert =new String(convert.getBytes("iso-8859-1"), "UTF-8")
String convert =new String(convert.getBytes(), "UTF-8")
答案 0 :(得分: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);
答案 1 :(得分: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);
}
});
}
}