有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从字节缓冲区将汉字读入字符串

所以我有一个char[]数组,它包含文本和其他数据

如何从char[]数组中提取中文文本?现在我可以用英语很好地学习

public String getString(int index, int length) {
    String str = "";

    for (int i = 0; i < length && this.data[index + i] != 0; i++)
        str = str + this.data[index + i];

    return str;
}

然后我试着这样做:

try {
    String charset = "GB18030";
    String str = new String(m.target.getBytes("UTF-16"), "GB18030");
    System.out.println(str);
    System.out.println(str.equals("大家"));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

m.target是我用上面的getString()从byte[]数组中得到的字符串。我尝试了各种编码和组合,但没有一种能正确显示文本(大家) 对于str.equals(“大家))

编辑

使用这种方法,我可以成功地获得汉字

public String test(int index, int length) {
    byte[] t = new byte[this.data.length];

    for (int i = 0; i < this.data.length; i++)
        t[i] = (byte) this.data[i];

    try {
        return new String(t, index, length, "GB18030");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

但我现在的问题是。。我以为一个字节的最大值是127?字节数组如何保存高字节汉字?我可以安全地将缓冲区更改为byte[]而不是char[]吗


共 (1) 个答案

  1. # 1 楼答案

    Java中的charString都是Unicode。只要在Java代码中对其进行操作,就不必关心这个问题。在转换为/从字节[]数组或读/写至/从IO流时指定编码

    要声明包含汉字的字符串,可以使用转义序列,也可以直接用代码编写,但必须注意文件编码UTF-8格式现在是准标准格式,它受到IDE(如Eclipse)和构建工具(maven、ant)的支持

    所以你就写吧

    char ch = '大';
    char[] chrs = new char[]{'大','家'};
    String str = "大家";
    

    要从例如UTF-16编码文件中读取汉字,可以使用InputStreamReader指定正确的编码,然后在BufferedReader的帮助下读取字符串

        BufferedReader reader = new BufferedReader(new InputStreamReader(
            new FileInputStream("myfile.txt"), "UTF-16"));