Skip to content
Advertisement

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;
        
            try{
                  
                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 = inputRead.read(buffer)) > 0){
                    
                    System.getProperty("line.separator");
                    
                    outWrite.write(buffer, 0, length);
                    
                    
                
            }

               
                inputRead.close();
                outWrite.close();
     
            
    }
    catch(IOException ioe){
                ioe.printStackTrace();
         }
        }

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

Advertisement

Answer

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) {
            outWrite.write(System.lineSeparator());
            String modifiedString = line.replaceAll("\d{4}-\d{2}-\d{2} \d{2}:\d{2}", dateTimeFormatter.format(LocalDateTime.now()));
            outWrite.write(modifiedString);
        }
    }

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
Advertisement