【发布时间】:2014-11-26 20:54:31
【问题描述】:
/*这个程序将学生序列化。 *如果文件存在,则程序加载它。 *否则它会创建一个新的班级列表。 *学生对象被添加到班级列表然后保存 */ 它是作业的一部分,但是我以前从未使用过 objectWriter。
import java.util.Scanner;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.ClassNotFoundException;
import java.util.List;
import java.util.ArrayList;
import java.io.EOFException;
public class ClassList{
public static void find(int sN, String fN, String lN){
boolean found = false;
try{
ObjectOutputStream objectOS = new ObjectOutputStream(new FileOutputStream("ClassList.data"));
ObjectInputStream objectIS = new ObjectInputStream(new FileInputStream("ClassList.data"));
int i=0;
Assignment readAssign = (Assignment) objectIS.readObject();
Student studentRead = readAssign.getStudents().get(i);
/*Search the student objects & compare student number.
*If found, boolean returns true, else the boolean is false
*/
while (readAssign.getStudents() != null){
studentRead = readAssign.getStudents().get(i);
if (studentRead.getID() == sN){
found = true;
break;
}
i++;
}
/*If the boolean found is true error message is produced
*If the boolean found is false then it adds a new Student object
*/
if (found = true){
System.out.println("A student with this id number already exists by the name:");
System.out.print(studentRead.getFName() + " " + studentRead.getLName());
objectOS.flush();
objectOS.close();
}
else{
Student student = new Student();
student.setFName(fN);
student.setLName(lN);
student.setID(sN);
Assignment assign = new Assignment();
List<Student> students = new ArrayList<>();
students.add(student);
assign.setStudents(students);
System.out.println("Done");
objectOS.writeObject(assign);
objectOS.flush();
objectOS.close();
}
}
catch(ClassNotFoundException cnf){
cnf.printStackTrace();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch(EOFException of) {
eof.printStackTrace();
}
catch(IOException ioe) {
//ioe.printStackTrace();
}
}
public static void main(String args[]){
Scanner stuIn = new Scanner(System.in);
//Use student Input to create students
System.out.println("What is your first name: ");
String fName = stuIn.nextLine();
System.out.println("What is your last name: ");
String lName = stuIn.nextLine();
System.out.println("What is your student number: ");
int sNum = stuIn.nextInt();
find(sNum, fName, lName);
}
}
错误信息:
java.io.EOFException 在 java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601) 在 java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) 在 java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) 在 ClassList.find(ClassList.java:28) 在 ClassList.main(ClassList.java:100)
【问题讨论】:
标签: java