我有一个UTF-8格式的字符串。我想将其转换为干净的ANSI格式。怎么做?
你可以这样做:
new String("your utf8 string".getBytes(Charset.forName("utf-8")));
在这种格式中,4个字节的UTF8
转换为8个字节的ANSI
通常不可能将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可以代表á和ç。