RandomAccessFile将int转换为中文

问题描述 投票:-1回答:1

我正在尝试阅读一些存储在txt文件中的书籍对象。当我运行它运行的代码但返回不正确的信息。

预期结果:Book isbn = 225346873945,price = 12.99,yearPublished = 2015,title ='Finders Fee'

Actual result: Book isbn=⸹㔬⁹敡牐毕汩独敤㴲〱〬⁴, 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());

}
java randomaccessfile
1个回答
0
投票

readInt()和朋友们都是二进制数据。你的文件是文字。您应该只读取此文件中的字节。 RandomAccessFile是一个糟糕的选择:使用BufferedReader而不是InputStreamReader而不是FileInputStreamreadLine()方法。

© www.soinside.com 2019 - 2024. All rights reserved.