Java 将int转换为中文的随机访问文件
我正在尝试读取一些存储在txt文件中的图书对象。当我运行代码时,它会运行,但返回不正确的信息 预期结果: 书名isbn=225346873945,价格=12.99,出版年份=2015年,书名为“查找者费用” 实际结果: 图书isbn=⸹㔬⁹敡牐畢汩獨敤㴲〱〬⁴, 价格=9.770698273454668E199,出版年份=1633907817,标题=捥映瑨攠坩汤❽䵂潯死楳扮㴲㈵㌴㘸㜳㤴㔬⁰物捥㴱㈮㤹Ⱐ祥慲' txt文件中的信息正确,但在控制台中显示时不正确。忽略无效的while循环,如何修复此代码Java 将int转换为中文的随机访问文件,java,randomaccessfile,Java,Randomaccessfile,我正在尝试读取一些存储在txt文件中的图书对象。当我运行代码时,它会运行,但返回不正确的信息 预期结果: 书名isbn=225346873945,价格=12.99,出版年份=2015年,书名为“查找者费用” 实际结果: 图书isbn=⸹㔬⁹敡牐畢汩獨敤㴲〱〬⁴, 价格=9.770698273454668E199,出版年份=1633907817,标题=捥映瑨攠坩汤❽䵂潯死楳扮㴲㈵㌴㘸㜳㤴㔬⁰物捥㴱㈮㤹Ⱐ祥慲' 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());
}
试试看{
bookFile.seek(0);
对于(图书对象:图书列表){
字符串tempBook=bookObj.toString();
bookFile.writeBytes(tempBook);
bookFile.writeBytes(System.getProperty(“line.separator”);
}
}捕获(IOE异常){
System.out.println(“写入”+书籍列表文件时出错);
}捕获(例外e){
System.out.println(“一般错误”+e);
}
试一试{
Book tempBook=新书();
bookFile.seek(0);
while(true){
readData(bookFile、tempBook);
System.out.println(tempBook.toString());
}
}捕获(IOE异常){
系统输出打印项次(“IO错误”+e);
}捕获(例外e){
System.out.println(“错误”+e.getMessage());
}
}
公共静态void readData(RandomAccessFile bookFile,Book Book)引发IOException、EOFEException、Exception
{
StringBuffer sb=新的StringBuffer();
对于(int i=0;ireadInt()
和friends是二进制数据。您的文件是文本。您应该从该文件中读取字节。RandomAccessFile
是一个糟糕的选择:在InputStreamReader
上使用BufferedReader
,在FileInputStream
上使用readLine()
method.您是如何编写数据的?如果您没有使用RandomAccessFile和相反的write*方法来编写数据,那么您可能正在使用二进制数据读取器读取文本文件。这不是一个好主意。请共享您用来编写数据的代码。您可以查看Scanner
类以从中读取各种数据类型一个文本文件。更新了帖子以显示写入方法。您的写入方法与readingOk的方法不匹配,您在平台默认编码中写入一个字符串,每个字符可能有一个字节,您正在使用每个字符读取两个字节的readChar
和读取二进制的readDouble/readInt读取它们您需要使用相应的写入方法写入数据(writeChar
,writeDouble
,writeInt
),或者您需要完全切换到使用PrintWriter和Scanner来写入和读取数据。