当我将编码设置为UTF-16时,为什么FileInputStream readline返回null?

时间:2015-04-16 10:22:30

标签: java encoding bufferedreader streamreader

它适用于UTF-8,如果我使用不同的文件,它也适用于UTF-16

BufferedReader br = new BufferedReader(new InputStreamReader(new 
FileInputStream(filePath), "UTF-16"));

如果我在上面的代码中将UTF-16替换为UTF-8,那么一切都按预期工作,为什么会这样?

建议的答案不同,因为我只需要阅读该文件。答案很简单,如果文件是UTF-8,我无法读取UTF-16。

1 个答案:

答案 0 :(得分:1)

检查文件的编码。 UTF-16可以使用Big Endian(UTF-16BE)或Little Endian(UTF-16LE)进行编码。这些是不同的。

此代码适用于同一文件的四种变体。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class SOPlayground {

    public static void main(String[] args) throws Exception {
        readAndPrint("/tmp/u-8.txt", Charset.forName("UTF-8"));
        readAndPrint("/tmp/u-16.txt", Charset.forName("UTF-16"));
        readAndPrint("/tmp/u-16le.txt", Charset.forName("UTF-16LE"));
        readAndPrint("/tmp/u-16be.txt", Charset.forName("UTF-16BE"));
    }

    private static void readAndPrint(String filePath, final Charset charset) throws IOException, FileNotFoundException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset));
        String line = br.readLine();
        while (line != null) {
            System.out.println(line);
            line = br.readLine();
        }
    }
}

在GNU / Linux上,您可以使用file工具检查编码:

/tmp % file u*.txt
u-16be.txt: data
u-16le.txt: data
u-16.txt:   Little-endian UTF-16 Unicode text, with no line terminators
u-8.txt:    UTF-8 Unicode text

这些文件的内容都不同:

/tmp % cat u*.txt
����
����
������
üäöü

但是使用上面的Java代码,可以正确读取它们。我的Java代码的输出是:

üäöü
üäöü
üäöü
üäöü