2014-02-13 3 views
0

자바에서 객체를 저장하고 읽으려고합니다. 지금여러 객체 저장 및 읽기

private JButton save = new JButton("save"); 
save.addActionListener(
      new ActionListener(){ 
       public void actionPerformed(ActionEvent arg0){ 
       sauvegarder();}}); 
read(); 

이 절약 ::::

ArrayList<projet> file = new ArrayList<projet>(); 


    public void sauvegarder(){ 

    projet pro = new projet (Integer.parseInt(a1.getText()),a2.getText(),a3.getText(),list1); 
     file.add(pro); 

     try { 
      FileOutputStream fileOut= new FileOutputStream("LES PROJETS.txt"); 
      ObjectOutputStream out = new ObjectOutputStream(fileOut) ; 

      for (projet a:file) 
       out.writeObject(a); 
      out.close(); 
     } 

      catch(Exception e) 
      {e.printStackTrace();} 

     JOptionPane.showMessageDialog(null, 
       " ^_^ FILE SAVED ^_^","save file", 
       JOptionPane.INFORMATION_MESSAGE);} 

방법에 대한 읽기 및 저장 개체의 방법 ...

방법 "sauvegarder는"::: 독서에 대한 "읽기"입니다

ArrayList<projet> file1 = new ArrayList<projet>(); 
JList l1 = new JList(); 


public void read(){ 
    ObjectInputStream in = null; 

    try { 
     FileInputStream fileIn = new FileInputStream("LES PROJETS.txt"); 
     in = new ObjectInputStream(fileIn) ; 
     while (true){  
      try{ 
       projet c =(projet) in.readObject(); 
       file1.add(c);} 
       catch(EOFException ex){// end of file case 

       break;} 
     }} 

     catch(Exception e) 
     {e.printStackTrace();} 
    finally{ 
     try { in.close(); 
     } 
      catch (IOException e) { 
       e.printStackTrace(); } }} 
    l1= new JList (file1.toArray()); 
      } 

읽기 및 저장이 제대로 작동하지만 문제는 두 명의 arraylists가 비어 있습니다! 나는 file.size() -> 0을 씁니다! 나는 객체를 저장했지만 .... "les projets. txt"파일에는 내가 저장 한 객체가 들어 있으며 JList는 arraylist에 객체를 표시합니다.

더하기 개체 (projet)를 저장하려고 할 때, 내가 저장 한 첫 번째 개체가 제거되고 새 개체가 저장됩니다. 누군가 나를 도와 줄 수 있습니까?

+0

file1에서 데이터를 기록 할 필요가 file1

ArrayList<projet> file1 = new ArrayList<projet>(); 

입니다. "파일"arraylist와 "file1"arraylist가 다른 목록이라는 것을 알고 있습니까? – Taylor

+0

@ 테일러 예 그들은 다릅니다! 이상한 것이 어디 있어요! – user3285843

+0

그게 문제였습니까? – Taylor

답변

0

문제는 당신이 당신이 그것에 아무것도 추가하지 않기 때문에 비어있는이 목록 file

ArrayList<projet> file = new ArrayList<projet>(); 
... 
for (projet a:file) 
    out.writeObject(a); 

로 쓰기 위해 노력하고있다. 목록 를 가지고있는 데이터는 당신이 당신의 코드에서 다른 곳에서 뭔가 이상한 일을하는지하지 file

+0

대단히 감사합니다. 완벽하게 작동합니다. – user3285843

+0

이제 최종 답변을 수락 해주십시오 : P –