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
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
This code reads entire file contents into a
List of String
s and changes the second line's content, then writes the list back to the file.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 theString
array back into the file.As proposed in the accepted answer to a similar question:
Based on your implementation, something similar to:
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
: