嘿,我使用来自 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";
}
输出凹痕--------------- 学生姓名:Becky O'Brien学生ID:DKIT26学生电话号码:0876126944