在文本文件中查找一行并进行编辑

时间:2016-02-26 18:44:11

标签: java rename file-writing

我有以下代码:

   String mID = jTextField1.getText();
   String mType = jComboBox1.getSelectedItem().toString();
   String mFName = jTextField2.getText();
   String mLName = jTextField3.getText();
   String mHomePhone = jTextField4.getText();
   String mMobilePhone = mPhone2.getText();
   String mEmail = jTextField6.getText();
   String mHomeAddress = jTextField7.getText();
   //Defines the new line of data
   String newLine = (mID + " | " + mType + " | " + mFName + " | " + mLName + " | "
   + mHomePhone + " | " + mMobilePhone + " | " + mEmail + " | " + mHomeAddress); 

    try {
        File inFile = new File("Members2.txt");
        BufferedReader br;
        FileReader reader;
        try (PrintWriter writer = new PrintWriter(new BufferedWriter( new FileWriter("Member2_Temp.txt", true)))) {
           br = new BufferedReader(new FileReader(inFile));
           reader = new FileReader("Members2.txt");
           String line;
           while (null != (line = br.readLine())) {
               if (newLine.equals(line)) {
                   newLine = line.replace(line, newLine);
               }
               // Always write the line, whether you changed it or not.
               writer.println(newLine);
           }
            br.close();
            reader.close();
            writer.close();
       }

        File tempFile = new File("Member2_Temp.txt");
        Path source = tempFile.toPath();
        Path newdir = inFile.toPath();
        Files.move(source, newdir, REPLACE_EXISTING);

        dispose();
        new Edit_Member_Final().setVisible(true);

    } catch (IOException ex) {
        Logger.getLogger(Edit_Member_Final.class.getName()).log(Level.SEVERE, null, ex);
    } 

问题在于它只将已编辑的行打印到文件中,而不打印其余未编辑的行。

如果我有4条记录,程序会因某种原因打印编辑行4次。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

修改

           BufferedReader br;
            try (PrintWriter writer = new PrintWriter(new BufferedWriter( new FileWriter("Member2_Temp.txt", true)))) {
               br = new BufferedReader(new FileReader(inFile));
               String line;

               while (null != (line = br.readLine())) {
                   if (newLine.equals(line)) {
                       line = line.replace(line, newLine);
                   }

                   // Always write the line, whether you changed it or not.
                   writer.println(line);
               }
                br.close();
                writer.flush();
                writer.close();

您正在编写newLine,只有在找到匹配项时才会有数据

writer.println(newLine);

您也应该像这样写line,添加else条件

if (newLine.equals(line)) {
    line= line.replace(line, newLine);
}

writer.println(line);