Question

I am reading two strings and a double from a text file, but keep throwing an EOFException. This is my code:

public static Book readBook(String pathname) throws IOException, FileNotFoundException{
      DataInputStream dis = new DataInputStream(
                                new BufferedInputStream(
                                    new FileInputStream(fn)));
      String theTitle = dis.readUTF();
      String theAuthor = dis.readUTF();
      double thePrice = dis.readInt();
      dis.close();
      return new Book(theTitle, theAuthor, thePrice);
   } 

Im really quite new to IO and have no idea on how to solve this exception, and throwing EOFExecption doesn't seem to work. Any help would be greatly appreciated, Cheers

EDIT: Stack Trace + File Contents

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readFully(Unknown Source)
    at java.io.DataInputStream.readUTF(Unknown Source)
    at java.io.DataInputStream.readUTF(Unknown Source)
    at Model.readBook(Model.java:48)
    at Model.runApp(Model.java:17)
    at Main.main(Main.java:8)

File Contents

name author 10.00 name2 author2 12.00

(In file they are all on seperate lines)

Was it helpful?

Solution

If this is text file, then you probably need to use Scanner:

Scanner scanner = new Scanner (new FileInputStream (fn));
String theTitle = scanner.nextLine ();
String theAuthor = scanner.nextLine ();
double thePrice = scanner.nextDouble ();
return new Book(theTitle, theAuthor, thePrice);

The code above expects title, author and price to be on separate lines.

OTHER TIPS

How is your text input formatted? Are you specifying the length of the strings to read in the input? My thinking is that you did not, or specified the length wrong, and are hitting the end of the file before on one of the subsequent reads.

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read.

http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html#readUTF()

I am reading two strings and a double from a text file

No you aren't. You are reading two writeUTF() results and an integer from a binary file. If it isn't a binary file, you are using the wrong code. You need to read the file line by line, split each line probably on the spaces, and parse the double using Double.parseDouble(). Or, use java.util.Scanner to make the whole thing easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top