Reputation: 9905
I have a java
program that creates a text file as follows:
FileWriter fstream = new FileWriter(filename + ".txt");
BufferedWriter outwriter = new BufferedWriter(fstream);
I add lines to the file by using
outwriter.write("line to be added");
Now at certain stages of the program I need to know how many lines I have added in the text file, while the file still has lines waiting to be added.
This whole process is to add some footer and header.
Is there any method that can find the current or last added line number?
EDIT
Adding a function
or a counter
to add lines is a solution but the time constraint doesn't allow me that. As I am dealing with hell lot of LOC
this would be a major change at a lot of places it would consume a lot of time.
Upvotes: 1
Views: 3977
Reputation: 3630
Create a method like this:
public int writeLine(BufferedWriter out, String message, int numberOfLines) {
out.write(message);
return numberOfLines++;
}
Then you can do this:
int totalLines = 0;
totalLines = writeLine("Line to be added", outwriter, totalLines);
System.out.println("Total lines: " + totalLines);
> "Total lines: 1"
Upvotes: 0
Reputation: 4701
Make a method which will write lines to the files
private static int lineCount;
private static void fileWriter(BufferedWriter outwriter, String line)
{
outwriter.write(line);
lineCount++;
}
Now each time you need to write a line to a file, then just call this method. And at any point in time you need to know the line count then lineCount
variable will do the concern.
Hope this helps!
Upvotes: 0
Reputation: 115328
Sure. Just implement your own writer, e.g. LineCountWriter extends Writer
that wraps other Buffered
and counts written lines.
Upvotes: 1
Reputation: 272237
Take a look at Apache Commons Tailer.
It will perform a tail
-like operation and call you back (via TailListener) for each line as lines are added to the file. You can then maintain your count in the callback. You don't have to worry about writing file reading/parsing code etc.
Upvotes: 2
Reputation: 5116
Make a counter:
lineCounter+="line to be added".split("\n").length-1
Upvotes: 0