27

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
0

4 Answers 4

39

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this tip. It's 2017 and I had still been relying on commons io
This should be the accepted answer. Straight forward and doesn't encounter an issue I had where the file went blank after reading from it with BufferedReader.
32

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

   }
}

1 Comment

no idea how this worked for you?! since for me it doesn't even create a file. To fix I create a new FileWriter parsing in a File instance rather than a file name string like this code does. So obviously move File newFile = new File(tmpFileName) before creating the FileWriter and use that File instance for the FileWriter. fixed it for me.
3

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.

1 Comment

what library isit in, its not working, List is not recognised either.
2

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.

1 Comment

im sure it can be done like above, i get the following error? any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.