Need a Java program that writes all changes made to a txt file into a log.txt file

StackOverflow https://stackoverflow.com/questions/22154259

  •  19-10-2022
  •  | 
  •  

Question

I know about the new WatchDir feature, but I want the changes made in the FILE and not Directory to be written into a log file. Any changes made to it are written directly into log.txt file. The current code I have: http://pastebin.com/GwURfRbi , writes only the last line into txt file because it is reading only one line. I need to tweak it in such a way that it reads a line, if changes is made writes into file, then again keeps reading, and as soon as any change is made, it is written in the txt file instantly. Can anyone help?

code:

import java.io.*;
public class LogMonitor { 
    public static void main(String[] args) throws Exception { 
        FileReader fr = new FileReader("D:/test.txt"); 
        BufferedReader br = new BufferedReader(fr); 
        while (true) { 
            String line = br.readLine(); 
            if (line == null) {
                Thread.sleep(1*1000); 
            } else { 
                byte[] y = line.getBytes(); 
                File g = new File("D:/abc.txt"); 
                OutputStream f = new FileOutputStream(g); 
                f.write( y );
            }
        } 
    } 
}
Was it helpful?

Solution

I think your problem is that you did not set the append boolean to true in your OutputStream. Try this:

OutputStream f = new FileOutputStream(g, true); 

so that it appends the line instead of overwriting the whole file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top