我正在尝试阅读一些存储在txt文件中的书籍对象。当我运行它运行的代码但返回不正确的信息。
预期结果: 预订isbn = 225346873945,价格= 12.99,yearPublished = 2015,title ='Finders Fee'
实际结果: 预订isbn =⸹㔬⁹牐毕汩敤敤〬⁴〬⁴price,price = 9.770698273454668E199,yearPublished = 1633907817,title ='捥映瑨攠煲汤❽䵂浔楳㴲㴲㴲㴲㈵㌴㜳㤴㤴㤴⁰物捥㴱㈮㤹Ⱐ祥慲'
txt文件中的信息是正确的,但是当它在控制台中显示时,它是不正确的。忽略无效的while循环,我该如何修复此代码?
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());
}
答案 0 :(得分:0)
readInt()
和朋友们都是二进制数据。你的文件是文字。您应该只读取此文件中的字节。 RandomAccessFile
是一个糟糕的选择:对BufferedReader
而不是InputStreamReader
和FileInputStream
方法使用readLine()
。