在 Java 中修改现有文件内容

2022-09-01 21:45:34

我想替换第二行文件内容,有人可以帮忙请基于下面的文件格式和监听器方法。

1324254875443
1313131
Paid
0.0

第二行很长,想要替换到 。currentTimeMillis()

/************** Pay Button Listener **************/
public class payListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        ArrayList<String> lines = new ArrayList<String>();
        String line = null;

        try {
            FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
            BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
            BufferedWriter bw = new BufferedWriter(fw);
            while ((line = br.readLine()) != null) {
                if (line.contains("1313131"))
                    line.replace(System.currentTimeMillis();
                lines.add(line);
                bw.write(line);
            }  //end if                 

        }     //end try
        catch (Exception e) {

        }  //end catch   
    }    //end while
}//end method

答案 1

正如在对类似问题的公认答案中所建议的那样:

同时以写入模式打开临时文件,并为每行读取它,必要时修改,然后写入临时文件。最后,删除原始文件并重命名临时文件。

根据您的实现,类似于:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ReplaceFileContents {
   public static void main(String[] args) {
     new ReplaceFileContents().replace();
   }

   public void replace() {
      String oldFileName = "try.dat";
      String tmpFileName = "tmp_try.dat";

      BufferedReader br = null;
      BufferedWriter bw = null;
      try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line;
         while ((line = br.readLine()) != null) {
            if (line.contains("1313131"))
               line = line.replace("1313131", ""+System.currentTimeMillis());
            bw.write(line+"\n");
         }
      } catch (Exception e) {
         return;
      } finally {
         try {
            if(br != null)
               br.close();
         } catch (IOException e) {
            //
         }
         try {
            if(bw != null)
               bw.close();
         } catch (IOException e) {
            //
         }
      }
      // Once everything is complete, delete old file..
      File oldFile = new File(oldFileName);
      oldFile.delete();

      // And rename tmp file's name to old file name
      File newFile = new File(tmpFileName);
      newFile.renameTo(oldFile);

   }
}

答案 2

尽管这个问题已经很老了,但我想补充一点,从Java 1.7开始,这可以更容易地实现:java.nio.file.Files

List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
    if (line.contains("1313131")) {
       newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
    } else {
       newLines.add(line);
    }
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);