gpt4 book ai didi

java - RandomAccessFile 打印到文本文件的麻烦

转载 作者:行者123 更新时间:2023-11-29 03:44:00 25 4
gpt4 key购买 nike

嘿,我正在使用 ArrayList 存储中的学生数组使用文件 i/o 写入文本文件。一切都很好。我有那个工作。但在实际的文本文件中,细节是在一行中打印和读取。

谁能看出问题所在。

这是我的代码:

主应用

import java.io.RandomAccessFile;



public class MainApp
{

public static void main(String[] args) throws Exception
{
new MainApp().start();

}
public void start()throws Exception
{
StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo@hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini@gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez@webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez@yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123@hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
//details.print();


RandomAccessFile file = new RandomAccessFile("ContactDetails.txt","rw");
//getBytes() returns an array of bytes.
//Because i have put the store in a static Array.(I done this because i could find no other
//Simple way to write a Student Object.)
//None of the methods of the RandomAccessFile write class worked with this.
Student[] students = {a,b,c,d,e};
for (int i = 0; i < students.length; i++)
{
byte[] bytes = students[i].toString().getBytes();
for(byte byteWrite : bytes)
{
file.writeByte(byteWrite);
}
}
final int Record_Length = 30;
int recordNumber = 1;
file.seek((recordNumber) * Record_Length);

String code ="";
for(int i = 0; i < 4; i++)
{
code += file.readLine();
}
System.out.println(code);
file.close();


}


}

到字符串

//---------------------------------------------------------------------------
// toString.
//---------------------------------------------------------------------------
public String toString()
{
return "---------------------------Student--------------------------- " +
"\nStudent Name:" + studentName +
"\nStudent Id:"+ studentId +
"\nStudent Telephone Number:"+ studentTelephoneNumber +
"\nStudent Email:" + studentEmail +"\n\n";
}

输出dent------------------------ 学生姓名:Becky O'Brien学号:DKIT26学生电话:0876126944

最佳答案

我认为不是写作搞砸了;

    String code ="";
for(int i = 0; i < 4; i++)
{
code += file.readLine();
}
System.out.println(code);

当你调用 readLine 时,它​​获取当前行,但你必须自己添加换行符 (\n),所以它应该是 file.readLine() + "\n"而不是 file.readLine( )

关于java - RandomAccessFile 打印到文本文件的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11834410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com