简体   繁体   English

在Java中读取txt文件时获取EOFException

[英]Get EOFException while reading a txt file in Java

I have Google for a while but I still get confused. 我在Google住了一段时间,但仍然感到困惑。 When I used FileOutputStream to write some texts into a txt file and then use FileInputStream to read my file, everything was right. 当我使用FileOutputStream将一些文本写入txt文件,然后使用FileInputStream读取我的文件时,一切都正确。 But when I typed some words manually to my txt file, and then save in UTF-8 format, I got EOFException. 但是,当我手动在txt文件中键入一些单词,然后以UTF-8格式保存时,出现了EOFException。 Here is my input code: 这是我的输入代码:

StringBuilder s = new StringBuilder();
FileInputStream inputStream = new FileInputStream("filename");
DataInputStream in = new DataInputStream(inputStream);
while (in.available()>0) {
    s.append(in.readUTF());
}
in.close();
System.out.println(s); 
  • A file that can be read by readUTF() must have been written by writeUTF() . 可以由readUTF()读取的文件必须已由writeUTF()写入。 Not by FileOutputStream . 不是通过FileOutputStream
  • A file written by writeUTF() is not a text file. writeUTF()写入的文件不是文本文件。 It is a file of sequences of 16-bit length words and strings in a modified encoding, as described in the Javadoc. 如Javadoc中所述,它是经过修改的编码的16位长度字和字符串序列的文件。
  • available() > 0 is not a valid test for end of file. available() > 0不是对文件结尾的有效测试。

As you state it's a text file, and as your code isn't working, I suggest you should be using BufferedReader.readLine() . 当您声明它是一个文本文件,并且由于您的代码不起作用时,我建议您应该使用BufferedReader.readLine() And no ready() tests. 而且没有ready()测试。 readLine() will return null at end of stream. readLine()将在流的末尾返回null。

Javadoc for DataInputStream says the following: "An application uses a data output stream to write data that can later be read by a data input stream". 用于DataInputStream的 Javadoc表示以下内容:“应用程序使用数据输出流来写入数据,以后可以由数据输入流读取”。 So it is probably not a good idea to read manually-written text from file using DataInputStream. 因此,使用DataInputStream从文件中读取手动编写的文本可能不是一个好主意。

Consider using FileInputStream#read() method if you need to read bytes or FileReader#read() if you need to read characters. 如果需要读取字节,请考虑使用FileInputStream#read()方法,如果需要读取字符,请考虑使用FileReader#read()

Consider using FileInputStream to read the file, ie: 考虑使用FileInputStream读取文件,即:

public static void main(String[] args) throws Exception {
    StringBuilder s = new StringBuilder();
    FileInputStream inputStream = new FileInputStream("file.txt");
    int content;
    while ((content = inputStream.read()) != -1) {
        s.append((char) content);
    }
    inputStream.close();
    System.out.println(s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM