2014-08-28 128 views
0

應用程序應該能夠註冊一個新用戶並將數據保存到已經有很多用戶數據的文本文件中。此代碼是有效的,但它不會將新數據保存到文本文件。我應該如何覆蓋文本文件?我應該先從文本中讀取數據並將所有數據寫回到文本文件,還是有辦法添加新行並在其中寫入新數據?用Java覆蓋文本文件

registerB.addActionListener(new ActionListener(){ 
         public void actionPerformed(ActionEvent e){ 
          String getFullname = fullnameT.getText(); 
          String getUsername = usernameT.getText(); 
          String getPassword = passwordT.getText(); 
          String getPN = pnT.getText(); 
          String getEmail = emailT.getText(); 
          boolean theSame = false; 
          String []Fullname = new String[20]; 
          String []Username = new String[20]; 
          String []Password = new String[20]; 
          String []PN = new String[20]; 
          String []Email = new String[20]; 

      if(!getFullname.isEmpty() && !getUsername.isEmpty() && !getPassword.isEmpty() && !getPN.isEmpty() && !getEmail.isEmpty()){ 
       int k = 0; 
       try { 
        Scanner in = new Scanner (new FileReader("login.txt", true)); 
        while (in.hasNext()) { 
         Fullname[k] = in.next(); 
         Username[k] = in.next(); 
         Password[k] = in.next(); 
         PN[k] = in.next(); 
         Email[k] = in.next(); 
         in.next(); 

         if(getUsername.equals(Username[k])){ 
          JOptionPane.showMessageDialog(null, "Username already has been registered."); 
          theSame = true; 
          break; 
         } 
         k++; 
        } 
       }catch(Exception ew){} 
       try 
       { 
        String path = "login.txt"; 

        File file = new File(path); 

        FileWriter fileWriter = new FileWriter(file,true); 

        BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter); 

        fileWriter.append("," + getFullname + "," + getUsername + "," + getPassword + "," + getPN + "," + getEmail +"," + "\n"); 

        bufferFileWriter.close(); 

        System.out.println("User Registration Completed"); 

       }catch(Exception ex){ 
        System.out.println(ex); 
       } 
      else{ 
       JOptionPane.showMessageDialog(null, "One or some of the fields is/are empty"); 
      } 
     } 
    }); 

文本文件的格式是這樣的

fullname,username,password,phonenumber,email fullname,username,password,phonenumber,email

+0

可能重複(http://stackoverflow.com/questions/1625234/how-to-在java中添加文本到現有文件) – 2014-08-28 18:05:09

回答

0

這是錯誤的new FileReader("login.txt", true)

FileReader確實有這個構造

變化new FileWriter("login.text")new FileWriter("login.text", true)

真正將新數據添加到現有的數據

的[如何將文本追加到Java中的現有文件]
+0

我已經試過了,仍然不保存 – user3053089 2014-08-28 18:06:10

+0

您的FileReader構造函數是錯的 – SparkOn 2014-08-28 18:12:35

+0

我看到它沒有包含FileWriter。 Thnx爲你提供幫助 – user3053089 2014-08-28 18:21:34