【问题标题】:First character of the reading from the text file :  [duplicate]从文本文件中读取的第一个字符: [重复]
【发布时间】:2013-06-28 14:45:49
【问题描述】:

如果我编写这段代码,我会得到它作为输出 --> 首先: 然后是其他行

try {
    BufferedReader br = new BufferedReader(new FileReader(
            "myFile.txt"));

    String line;
    while (line = br.readLine() != null) {
        System.out.println(line);
    }
    br.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

如何避免?

【问题讨论】:

  • 我猜是因为编码。
  • UTF-8 BOM
  • 我这样解决了: BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("dictionary.txt"),"UTF8")); if (line.startsWith("\uFEFF")) { line = line.substring(1); }
  • 不过,这会从每一行的开头去除 \uFEFF。我认为您只想删除文件开头的那个。

标签: java unicode character-encoding filereader


【解决方案1】:

你在第一行得到了字符,因为这个序列是UTF-8 byte order mark (BOM)。如果文本文件以 BOM 开头,则它很可能是由记事本等 Windows 程序生成的。

为了解决您的问题,我们选择将文件显式读取为 UTF-8,而不是任何默认的系统字符编码(US-ASCII 等):

BufferedReader in = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("myFile.txt"),
        "UTF-8"));

然后在 UTF-8 中,字节序列 解码为一个字符,即 U+FEFF。此字符是可选的 - 合法的 UTF-8 文件可能以它开头,也可能不以它开头。所以我们只会跳过第一个字符,如果它是 U+FEFF:

in.mark(1);
if (in.read() != 0xFEFF)
  in.reset();

现在您可以继续编写其余代码了。

【讨论】:

  • 如果我是正确的,BOM 字符在整个文件中只会出现一次?
  • 如果一个愚蠢的程序连接多个文件,每个文件都包含一个标题 BOM,它可能会发生多次。
【解决方案2】:

问题可能在于使用的编码。 试试这个:

BufferedReader in = new BufferedReader(new InputStreamReader(
      new FileInputStream("yourfile"), "UTF-8"));

【讨论】:

  • 我会说它肯定是编码;)
  • 我已经试过了。代替变成'?'
  • 这可能是因为您使用的是 IDE。有时他们会设置本机操作系统的默认编码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 2020-07-01
  • 2020-03-09
  • 2016-07-14
  • 2016-08-04
  • 2011-09-11
相关资源
最近更新 更多