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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23585083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:09:34  来源:igfitidea点击:

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

javastringutf-8ansi

提问by Xplosive

I have a string in UTF-8 format. I want to convert it to clean ANSI format. How to do that?

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

回答by Mike

Converting UTF-8 to ANSI is not possible generally, because ANSI only has 128 characters (7 bits) and UTF-8 has up to 4 bytes. That's like converting long to int, you lose information in most cases.

将 UTF-8 转换为 ANSI 通常是不可能的,因为 ANSI 只有 128 个字符(7 位),而 UTF-8 最多有 4 个字节。这就像将 long 转换为 int 一样,在大多数情况下您会丢失信息。

回答by EN20

You can do something like this:

你可以这样做:

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

in this format 4 bytes of UTF8converts to 8 bytes of ANSI

在这种格式中 4 字节UTF8转换为 8 字节ANSI

回答by gil.fernandes

You could use a java function like this one here to convert from UTF-8 to ISO_8859_1 (which seems to be a subset of ANSI):

您可以在此处使用像这样的 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);
}

Here is a simple test:

这是一个简单的测试:

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

This prints out:

这打印出来:

your utf8 stringá??

The ?character gets lost because it cannot be represented with ISO_8859_1 (it has 3 bytes when encoded in UTF-8). ISO_8859_1 can represent áand ?.

字符丢失,因为它不能用 ISO_8859_1 表示(用 UTF-8 编码时它有 3 个字节)。ISO_8859_1 可以代表á? .