I've got a service which runs all the time and also keeps a log file. It basically adds new lines to the log file every few seconds. I'm written a small file which reads these lines and then parses them to various actions. The question I have is how can I delete the lines which I have already parsed from the log file without disrupting the writing of the log file by the service?
Usually when I need to delete a line in a file then I open the original one and a temporary one and then I just write all the lines to the temp file except the original which I want to delete. Obviously this method will not word here.
So how do I go about deleting them ?
There are several ways you can delete a line, one simple method is to open two files, one in and one out. then copy line by line and skip the line you want to delete after you are done, delete the old file and rename the new one to the old name.
Scanner fileScanner = new Scanner(myFile); fileScanner. nextLine(); This will return the first line of text from the file and discard it because you don't store it anywhere.
Using the sed Command Removing the first line from an input file using the sed command is pretty straightforward. The sed command in the example above isn't hard to understand. The parameter '1d' tells the sed command to apply the 'd' (delete) action on line number '1'.
In most commonly used file systems you can't delete a line from the beginning of a file without rewriting the entire file. I'd suggest instead of one large file, use lots of small files and rotate them for example once per day. The old files are deleted when you no longer need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With