简体   繁体   English

为什么在使用 readUTF 读取时出现 EOF 异常?

[英]Why I am getting EOF exception when reading with readUTF?

I tried to read from a Textfile using DataInputStream and FileInputStream .我尝试使用DataInputStreamFileInputStream从 Textfile 中读取。 I know i should use FileReader instead but i wanted to try it with Byte streams.我知道我应该改用 FileReader,但我想尝试使用字节流。

here is the code这是代码

import java.io.*;

public class FTest_3 {

public static void main(String[] args) throws IOException{
    DataInputStream stream = new DataInputStream(new FileInputStream("lol1.txt"));
    String str = stream.readUTF();
    System.out.println(str);
    stream.close();
}   
}

If i try to read from the file lol1.txt , getting EOF Exception and readUTf(unknownsource) errors.如果我尝试从文件lol1.txt读取,出现EOF ExceptionreadUTf(unknownsource)错误。

But if I create a file lol1.txt using DataOutputStream and then read it using the above code, It works fine.但是如果我使用DataOutputStream创建一个文件lol1.txt然后使用上面的代码读取它,它工作正常。

Here is my code to Write file这是我写文件的代码

import java.io.*;

public class FTest_4 {

public static void main(String[] args) throws IOException{
    DataOutputStream stream = new DataOutputStream(new FileOutputStream("lol1.txt"));
    stream.writeUTF("hahah");
    stream.close();
 }  
}

Also I could not find any relevant post which could answer my query.我也找不到任何可以回答我的查询的相关帖子。 Thanks!谢谢!

readUTF is not a general-purpose method to read Strings from text files . readUTF 不是从文本文件中读取字符串的通用方法

It first reads two bytes that are supposed to contain the number of data bytes that follow (bytes, not characters).它首先读取两个字节,这两个字节应该包含后面的数据字节数(字节,而不是字符)。 After that come the bytes for the string in a modified UTF-8 encoding.之后是修改后的 UTF-8 编码中的字符串字节。

In your case, you were probably reading the two ASCII characters "ha" (0x68 0x61) at the beginning of your file, which is a pretty big number when interpreted as an integer, and then got an EOF because there were not enough bytes left in the file to match that.在你的情况下,你可能正在读取文件开头的两个 ASCII 字符“ha”(0x68 0x61),当解释为整数时这是一个相当大的数字,然后因为没有足够的字节而得到一个 EOF在文件中匹配它。

To read raw bytes, use one of the InputStream#read methods.要读取原始字节,请使用InputStream#read方法之一。

To read text files, use a Reader , not an InputStream .要读取文本文件,请使用Reader ,而不是InputStream Then you can read Strings as well.然后你也可以阅读字符串。

Try to use stream.read();尝试使用 stream.read(); for reading from a text file using DataInputStream or for specific values try to use stream.readDouble(), stream.readInt(), etc. and similarly try to use stream.write() for writing into a text file using DataOutputStream.要使用 DataInputStream 从文本文件读取或对于特定值,请尝试使用 stream.readDouble()、stream.readInt() 等,同样尝试使用 stream.write() 以使用 DataOutputStream 写入文本文件。

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

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