I am trying to read some book objects that I have stored in a txt file. When I run the code it runs but returns incorrect information.
Expected result: Book isbn=225346873945, price=12.99, yearPublished=2015, title='Finders Fee'
Actual result: Book isbn=⸹㔬⁹敡牐畢汩獨敤㴲〱〬⁴, price=9.770698273454668E199, yearPublished=1633907817, title='捥映瑨攠坩汤❽䵂潯死楳扮㴲㈵㌴㘸㜳㤴㔬⁰物捥㴱㈮㤹Ⱐ祥慲'
The information in the txt file is correct but when it is displayed in the console it is incorrect. Ignoring the invalid while loop, how can I fix this code?
try {
bookFile.seek(0);
for (Book bookObj : bookList) {
String tempBook = bookObj.toString();
bookFile.writeBytes(tempBook);
bookFile.writeBytes(System.getProperty("line.separator"));
}
} catch (IOException e) {
System.out.println("Error writing to " + BOOK_LIST_FILE);
} catch (Exception e) {
System.out.println("Generic error" + e);
}
try{
Book tempBook = new Book();
bookFile.seek(0);
while (true) {
readData(bookFile, tempBook);
System.out.println(tempBook.toString());
}
} catch (IOException e){
System.out.println("IO Error " + e);
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
}
public static void readData( RandomAccessFile bookFile, Book book) throws IOException, EOFException, Exception
{
StringBuffer sb = new StringBuffer();
for (int i=0; i<book.getISBN_LENGTH(); i++){
sb.append(bookFile.readChar());
}
book.setIsbn(sb.toString());
book.setPrice(bookFile.readDouble());
book.setYearPublished(bookFile.readInt());
sb.setLength(0);
for (int i = 0; i <book.TITLE_LENGTH ; i++) {
sb.append(bookFile.readChar());
}
book.setTitle(sb.toString());
}