Java上的Java Charset问题

前端之家收集整理的这篇文章主要介绍了Java上的Java Charset问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:我有一个包含特殊字符的字符串,我转换为字节,反之亦然.转换在 Windows上正常工作,但在linux上,特殊字符不能正确转换.linux上的默认字符集是UTF-8,如Charset所示. defaultCharset.getdisplayName()

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

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

编辑:我使用jdk1.6.13@H_404_3@

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

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@H_404_3@

解决方法

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

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

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.@H_404_3@

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

String x = "½";

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

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

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

javac -encoding ISO-8859-1 Foo.java

现在我们来看一下:@H_404_3@

System.out.println(x);

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

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

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

原文链接:https://www.f2er.com/java/121913.html

猜你在找的Java相关文章