如何在 java 中将字节 CP-1252 转换为字节 UTF-8

How can I convert byte CP-1252 to byte UTF-8 in java

我已经尝试过将字节 cp1252 转换为字节 utf8 但一切都是徒劳的。

例如:我有 byte[] 0xB5(cp1252),我想转换为 byte[] 0xC3, 0xA0(utf8)

我想点赞:µ --> à.

我的代码不起作用:

public void convert(){
  try {
      byte[] cp1252 = new byte[]{(byte) 0xB5};
      byte[] utf8= new String(cp1252, "CP-1252").getBytes("UTF-8");
      // values of utf8 array are 0xC2, 0xB5 not 0xC3, 0XA0 as I expected
  } catch (Exception ex) {
      System.out.println(ex.getMessage());
  }
}

您应该使用 "Cp1252" 作为代码页而不是 "CP-1252"

public void convert(){
    try {
        byte[] cp1252 = new byte[]{(byte) 0xB5};
        byte[] utf8= new String(cp1252, "Cp1252").getBytes("UTF-8");
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

Java supported encodings

正如所指出的那样0xB5您尝试解码的不是代码页 1252,上面的代码不会给您寻找的结果。

如果您 运行 下面的代码,您将看到没有编码可以进行您想要的转换

    try {
        byte[] u = new byte[]{(byte) 0xC3, (byte) 0xA0};

        SortedMap m = Charset.availableCharsets();
        Set k = m.keySet();
        Iterator i = k.iterator();
        String encoding = "";
        while (i.hasNext()) {
            String e = (String) i.next();
            byte[] cp = new String(u, "UTF-8").getBytes(e);
            if (cp[0] == (byte) 0xB5)
            {
                encoding = e;
                break;
            }
        }
        System.out.println(encoding);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }