如何在java中向现有文本文件添加信息

如何在java中向现有文本文件添加信息,java,arrays,oop,user-interface,netbeans-8,Java,Arrays,Oop,User Interface,Netbeans 8,我是初学者。我有一个已经有数据的文本文件,数据可以更新,但现在我想从另一个GUI表单添加更多数据,添加到数据末尾 现在看起来像这样 name//add/password//postcode//email//hpNo//Buyer 我想在行的末尾再添加一项 name//add/password//postcode//email//hpNo//Buyer//PAYMENT 我的当前代码创建新数据,而不是将其添加到最后一列: String addcash=""; try {

我是初学者。我有一个已经有数据的文本文件,数据可以更新,但现在我想从另一个GUI表单添加更多数据,添加到数据末尾

现在看起来像这样

name//add/password//postcode//email//hpNo//Buyer
我想在行的末尾再添加一项

name//add/password//postcode//email//hpNo//Buyer//PAYMENT
我的当前代码创建新数据,而不是将其添加到最后一列:

 String addcash="";

 try
 {
         File file = new File("MyAccount.txt");
         Scanner reader = new Scanner (file); 
         String line = "", oldtext = "", update = "";

         while(reader.hasNextLine())
         {
             line = reader.nextLine();

             String[] text = line.split("//");
             accNameTextField.setText(new User().getusername());

             if (text[0].equals(accNameTextField.getText())){
                  String update2 =  "//" + addcshComboBox.getSelectedItem(); 
                 addcash += accNameTextField.getText() + update2 + System.lineSeparator(); 

             }
             else
             {
                 addcash += line + System.lineSeparator();
             }
         }

         reader.close();

         FileWriter writer = new FileWriter("MyAccount.txt");
         writer.write(addcash);writer.close();
     }
     catch (IOException ioe)
     {
         ioe.printStackTrace();
     }
}

以下是解释:

要告诉
FileWriter
您希望追加文本,而不是覆盖现有文件,您需要向
FileWriter
构造函数添加一个参数,代码如下:

FileWriter writer = new FileWriter("MyAccount.txt", true); // Add the "true" parameter!
writer.write(addcash);
writer.close();

以下是解释:

要告诉
FileWriter
您希望追加文本,而不是覆盖现有文件,您需要向
FileWriter
构造函数添加一个参数,代码如下:

FileWriter writer = new FileWriter("MyAccount.txt", true); // Add the "true" parameter!
writer.write(addcash);
writer.close();
  • 需要系统知道那里有数据,然后跳到下一行,所以我在代码的这一部分添加了[text]
如果(文本[0].equals(accNameTextField.getText())){ 字符串更新2=“//”+文本[1]+“/”+文本[2]+“/”+文本[3]+“/”+文本[4]+“/”+文本[5]+“/”+文本[6]+“/”+添加CSHComboBox.getSelectedItem(); addcash+=accNameTextField.getText()+update2+System.lineSeparator();

  • 需要系统知道那里有数据,然后跳到下一行,所以我在代码的这一部分添加了[text]
如果(文本[0].equals(accNameTextField.getText())){ 字符串更新2=“//”+文本[1]+“/”+文本[2]+“/”+文本[3]+“/”+文本[4]+“/”+文本[5]+“/”+文本[6]+“/”+添加CSHComboBox.getSelectedItem();
addcash+=accNameTextField.getText()+update2+System.lineSeparator()

可能重复的@aleb2000我不明白在我传递给你的答案中有很好的解释,但是如果你不明白,我会给你写一个答案。@aleb2000我试过了,但它不起作用,我还需要在我的文本文件末尾添加文本,我将从文本中选择文本box@aleb2000组合框*可能重复@aleb2000我不理解tandIn我给你的答案解释得很好,但如果你不明白,我会给你写一个答案。@aleb2000我试过了,但它不起作用,我还需要在我的文本文件末尾添加文本,我将从文本文件中选择文本box@aleb2000组合框*我尝试过它不起作用,而且我需要在我的文本文件末尾添加文本,我将从文本框中拾取我尝试过它不起作用,而且我需要在文本文件末尾添加文本,我将从文本框中拾取该文本