2013-01-13 15 views
2

我很困惑我怎樣才能保存我的數據,例如我hava(Student ID,Name,Surname)唯一的學生ID是Integer,我想將這些數據保存到文本文件當我按(AddButtton),然後我想當我按下(UpdateButton)時更新這些數據,數據將被保存,但每次當數據保存括號出現在文件中並且按下(UpdateButton)時,數據都不會返回到我的TextField更新。如何使用隨機訪問文件將數據保存在文本文件中並更新這些數據?

 class BtnListenerAdd implements ActionListener{ 
     public void actionPerformed(ActionEvent a) { 

     if (a.getSource()==btnAdd){ 
      Student s=new Student(tfname.getText(),tfsurname.getText()); 
      s.number=Integer.parseInt(tfno.getText()); 
      myVector.add(s); 
       //System.out.println(s); 

      try{ 
       java.io.RandomAccessFile raf = 
           new java.io.RandomAccessFile("e:\\random.txt", "rw"); 


        for (int i = 0; i < myVector.size(); i++) { 
         raf.writeChars(myVector.toString()); 
        } 

        raf.seek(0); 
        while (raf.getFilePointer() < raf.length()) { 
         System.out.println(raf.readChar()); 
        } 

       raf.close(); 
      }catch(Exception e){ 
       System.out.println(e.toString()); 
      } 
     } 

     if (a.getSource()==btnList){ 
      ta1.setText(""); 
      for (Student s : myVector) { 
       ta1.append(s.toString()+ "\n"); 
      } 
     }   
     } 

    } 


    class BtnListenerUpdate implements ActionListener{ 

    public void actionPerformed(ActionEvent s) { 

     if (s.getSource()==btnUpdate){ 
      Student l=new Student(tfname.getText(),tfsurname.getText()); 
      l.number=Integer.parseInt(tfno.getText()); 
      myVector.add(l); 


      try{ 
       java.io.RandomAccessFile raf = 
           new java.io.RandomAccessFile("e:\\random.txt", "rw"); 

       for(int i=0; i <myVector.size(); i++) { 
        raf.writeChar(myVector.size()); 
       } 

       raf.seek(0); 
       int no= raf.readInt(); 
       tfno.setText(no + ""); 
       System.out.println(no); 


       String nam = ""; 
       for(int x=0; x<50; x++){ 
        nam += raf.readChar(); 
       } 


       nam = ""; 
       for(int x=0; x<50; x++){ 
        nam += raf.readChar(); 
       } 


      }catch(Exception e){ 
       System.out.println(e.toString()); 
      } 
     } 

    } 


    } 
+1

爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

2

如果您沒有創建或更新很多記錄,我建議您使用BufferedWriter。如果你是,我建議你使用數據庫,如MongoMySQL

而且,你可能還想用UTF-8數據開始測試你的代碼。變音等等。 :)

0

我建議你在編寫任何更多的代碼之前先編寫少量的代碼。您編寫的代碼越多,您對修復的難度越困惑。

我會重新開始編寫另一個單元測試的類,它以最簡單的可寫代碼開始,當它工作時再添加一點並測試它。

不幸的是你寫的一些代碼只是無稽之談,這就是爲什麼我不會重用它的任何一個。

+0

好的彼得,你可以編輯我的代碼我更biggener – salih

+0

我不會編輯代碼,因爲「我不會重用任何它。」你需要學習如何編寫你理解的代碼,這對我來說不會幫你寫。你寫的代碼看起來有一套你已經複製的代碼,這就是爲什麼你在這個混亂開始。我會幫你編寫代碼並編寫單元測試,但是爲你編寫它只會讓你的事情變得更糟。 –

+0

不,我自己寫了代碼,我告訴你編輯給我的程序不是寫給我的 – salih

相關問題