我构建了一个 Java GUI 应用程序,并且有一些带有 Unicode 文本的 jLabel
。当我从 NetBeans IDE 运行应用程序时,文本显示为正确的形式,但是当我从 .jar
文件运行时,文本显示为变形的形式。
我的代码:
try {
jLabel1.setText(new String("ژمارا ناسنامی".getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(dataEntry.class.getName()).log(Level.SEVERE, null, ex);
}
输出:
最佳答案
仅尝试此操作:
jLabel1.setText("ژمارا ناسنامی");
事实上,您的错误是首先使用 默认编码 使用 getBytes()
对您的 String
进行编码,然后将其解码为 UTF-8
,这是不正确的,因为您依赖的默认编码不能是 UTF-8
并且无用,因为 String
已经是 UTF-16
编码的,因此它已经覆盖了阿拉伯字符。
这是方法 String#getBytes() 的 Javadoc提醒一下:
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
如果你想正确编码String
,你需要使用String#getBytes(Charset)或String#getBytes(String)反而。但再一次,在这种特殊情况下甚至不需要它。
关于java - 当我在 jar 文件上运行时,Unicode 未显示在我的应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932296/