【问题标题】:How to add information to existing text file in java如何在java中向现有文本文件添加信息
【发布时间】:2017-01-23 20:11:36
【问题描述】:

我是初学者。我有一个文本文件,其中已经包含数据并且可以更新数据,但现在我想从另一个 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();
     }
}

【问题讨论】:

  • @aleb2000 我不明白
  • 在我通过你的答案中解释得很好,但如果你不明白我会为你写一个答案。
  • @aleb2000 我试过它不起作用,而且我需要在我的文本文件末尾添加文本,我将从文本框中选择
  • @aleb2000 组合框*

标签: java arrays oop user-interface netbeans-8


【解决方案1】:

解释如下:

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

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

【讨论】:

  • 我试过它不起作用,而且我需要在我的文本文件末尾添加文本,我将从文本框中选择
【解决方案2】:
  • 需要系统知道那里有数据并跳到下一行,所以我在这部分代码中添加了[文本]

if (text[0].equals(accNameTextField.getText())){ 字符串 update2 = "//" + text[1] +"//"+ text[2] +"//"+ text[3] +"//"+ text[4] +"//"+ text[ 5] +"//"+文本[6] +"//"+addcshComboBox.getSelectedItem(); addcash += accNameTextField.getText() + update2 + System.lineSeparator();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多