2013-01-24 52 views
-1

我要實現目標文件Java項目,但我(另存爲一切OK)從Java文件加載錯誤?

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"); 
    } 
} 

這是我用來加載文件的代碼有問題,當談到加載文件。該程序將加載只有我的文件中的最後2條記錄。這個想法是,我將它們全部加載到數組列表中以備將來在程序中使用。此外,我沒有收到我的任何回扣。任何幫助?謝謝:)

+0

您不存儲首先檢索到的Student實例(就在while之前)in stud1集合。難道這個文件只包含3條記錄嗎? – Henrik

+0

您認爲要裝入多少個物體?發佈文件的內容。 – TechSpellBound

回答

0

你永遠不添加到列表中,你讀

Student tempStudent = (Student) studentStream.readObject(); 
     while (endOfFile != true) 
     { 
      try 
      { 

       tempStudent = (Student) studentStream.readObject(); 
       stud1.add(tempStudent); 
      } 

第一個學生的同時,之前取出讀,像下面

 while (endOfFile != true) 
    { 
     try 
     { 

      Student tempStudent = (Student) studentStream.readObject(); 
      stud1.add(tempStudent); 
     } 

的代碼,我不知道如果這將解決您的問題

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(); 
+0

我這樣做,使用文件中的每個對象的.add方法 –

+0

請檢查我的編輯 –