java - windows-1252 到 UTF-8

标签 java character-encoding

下面是我尝试使用的代码,它给我的输出是:

RetValue: á, é, í, ó, ú, ü, ñ, ¿ Value: á, é, í, ó, ú, ü, ñ, ¿ ConvertValue: ?, ?, ?, ?, ?, ?, ?, ?

这不是想要的输出。我认为这里的每个字符的输出都应该是这种类型的 %C3%。

public static void main(String[] args) {
    String value = "á, é, í, ó, ú, ü, ñ, ¿";
    String retValue = "";
    String convertValue = "";
    try {
        retValue = new String(value.getBytes(),
        Charset.forName("Windows-1252"));
        convertValue = new String(retValue.getBytes("Windows-1252"),
        Charset.forName("UTF-8"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("RetValue: " + retValue + " Value: " + value
         + " ConvertValue: " + convertValue);
}

最佳答案

我了解到您正在尝试将您的文本从默认编码编码为 Windows-1252,然后编码为 UTF-8。

根据 String 类的 javadoc

String(byte[] bytes, Charset charset)

Constructs a new String by decoding the specified array of bytes using the specified charset.

因此,您所做的是将默认编码的文本解码为 Windows-1252,然后将新获得的文本进一步解码为 UTF-8。这就是它呈现异常的原因。

如果您的目的是从 Windows-1252 编码为 UTF-8,我建议您使用以下方法和 java.nio 包中的 CharsetEncoder:

public static void main(String[] args) {
    String value = "á, é, í, ó, ú, ü, ñ, ¿";
    String retValue = "";
    String convertValue2 = "";
    ByteBuffer convertedBytes = null;
    try {
        CharsetEncoder encoder2 = Charset.forName("Windows-1252").newEncoder();
        CharsetEncoder encoder3 = Charset.forName("UTF-8").newEncoder();             
        System.out.println("value = " + value);

        assert encoder2.canEncode(value);
        assert encoder3.canEncode(value);

        ByteBuffer conv1Bytes = encoder2.encode(CharBuffer.wrap(value.toCharArray()));

        retValue = new String(conv1Bytes.array(), Charset.forName("Windows-1252"));

        System.out.println("retValue = " + retValue);

        convertedBytes = encoder3.encode(CharBuffer.wrap(retValue.toCharArray()));
        convertValue2 = new String(convertedBytes.array(), Charset.forName("UTF-8"));
        System.out.println("convertedValue =" + convertValue2);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我获得了以下输出:

value = á, é, í, ó, ú, ü, ñ, ¿

retValue = á, é, í, ó, ú, ü, ñ, ¿

convertedValue =á, é, í, ó, ú, ü, ñ, ¿

关于java - windows-1252 到 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484064/

相关文章:

unicode - 竞争对编码和字符集的理解

使用 DOMDocument 进行 PHP 编码

string - 我可以破坏 []byte 和字符串之间的数据转换吗?

java - 简单计算返回 NullPointer 异常...为什么?

幕后的 Java 不可变性

java代码删除多余的正斜杠

java - Java代码中用来防止其被复制,粘贴和编译的不可识别字符列表

python - 统一码编码错误 : 'ascii' codec can't encode character '\xe9' when printing in UTF-8 locale

java - Java 有朴素的时间戳吗?

java - 将颜色层添加到 mandelbrot 集