微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java上的Java Charset问题

问题:我有一个包含特殊字符的字符串,我转换为字节,反之亦然.转换在 Windows上正常工作,但在linux上,特殊字符不能正确转换.linux上的认字符集是UTF-8,如Charset所示. defaultCharset.getdisplayName()

但是如果我使用选项-Dfile.encoding = ISO-8859-1在linux上运行,它可以正常工作

如何使用UTF-8认字符集使其工作,而不在unix环境中设置-D选项.

编辑:我使用jdk1.6.13

编辑:代码
使用cs =“ISO-8859-1”;或cs =“UTF-8”;胜利但不是在linux

String x = "½";
        System.out.println(x);
        byte[] ba = x.getBytes(Charset.forName(cs));
        for (byte b : ba) {
            System.out.println(b);
        }
        String y = new String(ba,Charset.forName(cs));
        System.out.println(y);

〜问候
DAED

解决方法

您的角色可能会被编译过程损坏,您的类文件中的垃圾数据将会结束.

if i run on linux with option -Dfile.encoding=ISO-8859-1 it works properly..

The “file.encoding” property is not required by the J2SE platform specification; it’s an internal detail of Sun’s implementations and should not be examined or modified by user code. It’s also intended to be read-only; it’s technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

总之,不要使用-Dfile.encoding = …

String x = "½";

由于U 00bd(½)将由不同的编码表示为不同的值:

windows-1252     BD
UTF-8            C2 BD
ISO-8859-1       BD

…你需要告诉编译器你的源文件的编码方式是:

javac -encoding ISO-8859-1 Foo.java

现在我们来看一下:

System.out.println(x);

作为PrintStream,这将在发送字节数据之前将数据编码为系统编码.喜欢这个:

System.out.write(x.getBytes(Charset.defaultCharset()));

这可能或可能不符合您预期的some platforms – 字节编码必须与控制台期望正确显示字符的编码相匹配.

原文地址:https://www.jb51.cc/java/121913.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐