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)
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.