【问题标题】:While reading from file in java, input is prefixed by two junk characters在java中读取文件时,输入以两个垃圾字符为前缀
【发布时间】:2018-03-01 04:50:12
【问题描述】:
FileInputStream fin = new FileInputStream("D:\\testout.txt");    
BufferedInputStream bin = new BufferedInputStream(fin);    
int i;    
while((i = bin.read())!=-1) {    
    System.out.print((char)i);    
}    

bin.close();    
fin.close();    

输出:ÿþGreat

我检查了文件 testout.txt,它只包含一个单词,即Great

【问题讨论】:

标签: java file utf-8


【解决方案1】:

这很可能是 Byte order mark,可选但允许在使用 UTF-8 字符编码的文件中。有些程序(例如记事本)考虑了这种可能性,有些则没有。默认情况下,Java 不会剥离它们。

解决此问题的一个实用程序是来自 Apache Commons IO 的 BOMInputStream

另外,当您将文件保存为 UTF-8 时,记事本会在文件中写入字节顺序标记。

【讨论】:

    【解决方案2】:

    ÿþ 是 UTF-16 中的 byte order mark。您可以使用 java.io 将字符串转换为 UTF-8,如 here 所述。

    您也可以参考answer了解更多详情。

    【讨论】:

      【解决方案3】:

      请使用 utf-8 字符编码来解决此类问题。 byte[] utf_8 = input.getBytes("UTF-8"); // 将 unicode 字符串转换为 UTF-8 字符串测试 = 新字符串(utf_8);

      【讨论】:

        【解决方案4】:

        当您使用文本时,您应该使用阅读器。例如。

        try(
            BufferedReader reader = Files.newBufferedReader(
                Paths.get("D:\\testout.txt"), 
                StandardCharsets.UTF_8)
            ){
            int i;    
            while((i = reader.read())!=-1) {    
                System.out.print((char)i);    
            }  
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-07
          • 1970-01-01
          • 2013-10-10
          • 2017-06-13
          • 2016-03-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多