2014-02-19 87 views
2

我正在創建一個GUI,並且使用Student對象返回數據類型的方法「getStudentInfo()」從JTextFields中檢索信息並將它們存儲到「student」對象中。如何更新二進制文件

public Student getStudentInfo() { 
    Student student = new Student(); 

    String name = jtfName.getText(); 
    student.setName(name); 

    String idNumber = jtfIDNumber.getText(); 
    student.setIdNumber(idNumber); 

    String address = jtfAddress.getText(); 
    student.setAddress(address); 

    String phoneNumber = jtfPhoneNumber.getText(); 
    student.setPhoneNumber(phoneNumber); 

    String major = jtfMajor.getText(); 
    student.setMajor(major); 

    return student; 
} 

然後,在不同的類中,我創建一個「添加」按鈕,點擊後,應該加上「學生」對象到一個ArrayList,然後寫的ArrayList成一個二進制文件。

private class AddButtonListener implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 
     File studentFile = new File(FILENAME); 

     ArrayList<Student> studentList = new ArrayList<Student>(); 
     studentList.add(text.getStudentInfo()); 

     try { 
      FileOutputStream fos = new FileOutputStream(studentFile); 
      ObjectOutputStream oos = new ObjectOutputStream(fos); 
      oos.writeObject(studentList); 
     } 

     catch (FileNotFoundException fnf) { 
      fnf.printStackTrace(); 
     } 

     catch (IOException ioe) { 
      ioe.printStackTrace(); 
     } 


    } 
} 

但是當我運行該程序,我寫了一個學生的信息並將其添加到二進制文件,然後我去添加其他的學生,它完全覆蓋前面的學生的信息。任何幫助將不勝感激。

回答

0

在你的類,AddButtonListener的actionPerformed方法,你有下面的代碼行:

FileOutputStream fos = new FileOutputStream(studentFile); 

所以字節寫入到文件的開頭此構造方法將打開該文件。由於每次單擊該按鈕時都會重新打開該文件,因此您正在用新數據替換文件內容。相反,使用的構造與附加字節,而不是覆蓋布爾參數...

FileOutputStream fos = new FileOutputStream(studentFile, true); 

您可以檢查出這個構造的細節Java文檔...

FileOutputStream constructor documentation