小编典典

用Java修改现有文件内容

java

我想替换第二行的文件内容,请根据以下文件格式和侦听器方法来帮助您。

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

阅读 460

收藏
2020-09-08

共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);

   }
}
2020-09-08