Skip to content

Replace Timestamp in Written Text File

I need to read a file and write it in a new file, the file that I read has it own time stamp, but in the written file I need to replace it with the current time eg( 2020-09-20 19:30 change it to 2020-09-30 01:30) I have been able to read and write it using the following code, but I am struggling with the change time stamp part

            FileInputStream inputRead = null;
            FileOutputStream outWrite = null;
                File infile =new File("test.txt");
                File outfile =new File("test_log.txt");
                inputRead = new FileInputStream(infile);
                outWrite = new FileOutputStream(outfile);
                byte[] buffer = new byte[2048];
                int length;             
                while ((length = > 0){
                    outWrite.write(buffer, 0, length);

    catch(IOException ioe){

Sorry forgot to mention the Line Read is as follows ” 20-09-2020 19:30 (Some Parameter) ” to “(current date) + (Some Parameter)



Try this

    File infile = new File("test.txt");
    File outfile = new File("test_log.txt");
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    try (
            BufferedReader inputRead = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));
            BufferedWriter outWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile)))
    ) {
        String line;
        while ((line = inputRead.readLine()) != null) {
            String modifiedString = line.replaceAll("\d{4}-\d{2}-\d{2} \d{2}:\d{2}", dateTimeFormatter.format(;

Expanding my answer a bit for clarity.
I’ve added try-with-resources, you don’t need to close the streams manually which should otherwise be done in a finally (if it crashes they are left open).
I’ve added readers which is a higher level api on top of the stream. for convenience.
I’ve added search and replace on the string using regex that matches your example string. In my example above i’m using strings which could probably be optimized if needed.

1 People found this is helpful