Modifying existing file content in Java

2020-01-25 00:48发布

I want to replace the second line file content, can somebody help please based on the below file format and listener method.

1324254875443
1313131
Paid
0.0

2nd line is long and want to replace to 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

4条回答
来,给爷笑一个
2楼-- · 2020-01-25 01:00

I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:

File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);

This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.

查看更多
迷人小祖宗
3楼-- · 2020-01-25 01:11

I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-25 01:15

As proposed in the accepted answer to a similar question:

open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.

Based on your implementation, something similar to:

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

   }
}
查看更多
5楼-- · 2020-01-25 01:25

Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with 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);
查看更多
登录 后发表回答