在java中将字符串从一种编码解释为另一种编码

时间:2016-09-01 04:06:13

标签: java string encoding utf-8

我四处寻找答案(我确定他们在那里),我不确定是否可能。

所以,我收到了一个包含“för”字样的巨大文件。我正在使用RandomAccessFile,因为我知道它的位置(种类),因此可以使用seek()函数到达那里。

要知道我发现它我的程序中有一个字符串“för”,我检查是否相等。这是问题,我运行调试器,当我得到“för”时,我得到的比较是“för”。

所以我的程序终止而没有找到任何“för”。

这是我用来获取单词的代码:

    private static String getWord(RandomAccessFile file) throws IOException {
    StringBuilder stb = new StringBuilder();
    String word;
    char c;
    c = (char)file.read();
    int end;
    do {
        stb.append(c);
        end = file.read();
        if(end==-1)
            return "-1";
        c = (char)end;

    } while (c != ' ');
    word = stb.toString();
    word.trim();
    return word;
}

所以基本上我将所有字符从文件中的当前点返回到第一个''字符。所以基本上我得到了这个词,但是因为(char)file.read();读取一个字节(我认为),UTF-8'ö'成为两个字符'Ã'和'¶'?

这种猜测的一个原因是,如果我用UTF-8编码打开我的文件,它就是“för”但是如果我在同一个地方用ISO-8859-15打开文件,我们现在正好具有我的getWord方法返回的内容: “för”

所以我的问题:

当我坐着“för”和“för”时,有什么方法可以解决这个问题吗?就像说“读”för“好像是一个UTF-8字符串”得到“för”?

3 个答案:

答案 0 :(得分:3)

If you have to use a RandomAccessFile you should read the content into a byte[] first and then convert the complete array to a String - somthing along the lines of:

byte[] buffer = new byte[whatever];
file.read(buffer);
String result = new String(buffer,"UTF-8");

This is only to give you a general impression what to do, you'll have to add some length-handling etc.

This will not work correctly if you start reading in the middle of a UTF-8 sequence, but so will any other method.

答案 1 :(得分:1)

您正在使用RandomAccessFile.read()。这读取单个字节。 UTF-8有时会为一个字符使用几个字节。

这里讨论从RandomAccessFile读取UTF-8的不同方法:Java: reading strings from a random access file with buffered input

如果您不一定需要RandomAccessFile,您一定要切换到读取字符而不是字节

如果可能,我建议Scanner.next()默认搜索下一个字。

答案 2 :(得分:-2)

import java.nio.charset.Charset;
String encodedString = new String(originalString.getBytes("ISO-8859-15"), Charset.forName("UTF-8"));