我必须为java项目实现Object Files,但是在加载文件时我遇到了麻烦(保存就可以了)
public static void loadStudentList() {
boolean endOfFile = false;
try {
// create a FileInputStream object, studentFile
FileInputStream studentFile = new FileInputStream("Students.obf");
// create am ObjectImnputStream object to wrap around studentStream
ObjectInputStream studentStream = new ObjectInputStream(studentFile) ;
// read the first (whole) object with the readObject method
Student tempStudent = (Student) studentStream.readObject();
while (endOfFile != true) {
try {
tempStudent = (Student) studentStream.readObject();
stud1.add(tempStudent);
}
catch(EOFException e) {
endOfFile = true;
}
}
studentStream.close();
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
}
catch(FileNotFoundException e) {
System.out.println("File not found");
}
catch(ClassNotFoundException e) { // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) { //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object
System.out.println("Unreadable File Format");
}
catch(IOException e) {
System.out.println("There was a problem reading the file");
}
}
这是我用来加载文件的代码。该程序将加载 ONLY 我文件中的最后2条记录。想法是我将所有这些加载到数组列表中以供将来在程序中使用。此外,我没有得到任何回收。有帮助吗?谢谢:))
答案 0 :(得分:0)
为什么不将对象添加到ArrayList<Type>
,然后将它们写入/序列化为文件
然后读取/反序列化它,将数据读入一个ArrayList<Type>
。
然后你可以从ArrayList
逐个获取你的对象这可能是一种更容易解决问题的方法。
//Serialize
ArrayList<Student> students = new ArrayList<Student>();
//Add the student objects to the array list
File f = new File("FileName.ser");
ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream(f));
objOut.writeObject(students);
//Deserialize
ArrayList<Student> students = new ArrayList<Student>();
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(new File("FileName.ser")));
students = (ArrayList<String>) objIn.readObject();
答案 1 :(得分:0)
您永远不会在列表中添加您读过的第一个学生
Student tempStudent = (Student) studentStream.readObject();
while (endOfFile != true)
{
try
{
tempStudent = (Student) studentStream.readObject();
stud1.add(tempStudent);
}
删除while之前的读取,如下面的代码
while (endOfFile != true)
{
try
{
Student tempStudent = (Student) studentStream.readObject();
stud1.add(tempStudent);
}
我不确定这是否能解决您的问题