简体   繁体   中英

Why I am getting EOF exception when reading with readUTF?

I tried to read from a Textfile using DataInputStream and FileInputStream . I know i should use FileReader instead but i wanted to try it with Byte streams.

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.

But if I create a file lol1.txt using DataOutputStream and then read it using the above code, It works fine.

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 .

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.

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.

To read raw bytes, use one of the InputStream#read methods.

To read text files, use a Reader , not an InputStream . Then you can read Strings as well.

Try to use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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