繁体   English   中英

如何在Java中将字符串UTF-8转换为ANSI?

[英]How to convert a string UTF-8 to ANSI in java?

我有一个UTF-8格式的字符串。 我想将其转换为干净的ANSI格式。 怎么做?

您可以执行以下操作:

new String("your utf8 string".getBytes(Charset.forName("utf-8")));

以这种格式, UTF8 4个字节转换为ANSI 8个字节

通常无法将UTF-8转换为ANSI,因为ANSI仅具有128个字符(7位),而UTF-8最多具有4个字节。 这就像将long转换为int,在大多数情况下,您会丢失信息。

您可以在此处使用这样的Java函数将UTF-8转换为ISO_8859_1(似乎是ANSI的子集):

private static String convertFromUtf8ToIso(String s1) {
    if(s1 == null) {
        return null;
    }
    String s = new String(s1.getBytes(StandardCharsets.UTF_8));
    byte[] b = s.getBytes(StandardCharsets.ISO_8859_1);
    return new String(b, StandardCharsets.ISO_8859_1);
}

这是一个简单的测试:

String s1 = "your utf8 stringáçﬠ";
String res = convertFromUtf8ToIso(s1);
System.out.println(res);

打印输出:

your utf8 stringáç?

字符会丢失,因为它无法用ISO_8859_1表示(以UTF-8编码时有3个字节)。 ISO_8859_1可以表示áç

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM