Reputation: 105
I want to use something like BufferedReader to read lines from a file but if the last line in the file does not end with a newline character, I would like it to be ignored. The standard BufferedReader will return the last line up to EOF, which is not what I want. So far, the best thing I've come up with is to copy the BufferedReader source, modify one line about handling EOFs and call it something like BufferedCompleteLineReader.. this doesn't seem very good though. Does anyone have a better idea?
The background is there are multiple readers making requests to read a file that is periodically appended with a new line of text (i.e. a log file) but each new line is only valid if it ends with a newline char. If I read the last line while it's being modified I'll get bad data. But I don't want to impose file locking because performance is more important to me than completeness (for the reader).
Upvotes: 1
Views: 4011
Reputation: 91
Create a custom subclass of FilterReader and put it between the BufferedReader and the actual file Reader/InputStream. In your filter reader, stash a copy of the last few chars on every read(char[]) call (i say last few chars in case you need to handle newlines which are more than 1 char, e.g. windows). after you read the last line, check the last chars stashed in your FilterReader to see if they represent a newline.
Upvotes: 1
Reputation: 1500155
Can't you just do it on the calling side, where you're reading and processing the data?
String nextLine = reader.readLine();
String currentLine = nextLine;
while ((nextLine = reader.readLine()) != null)
{
// Use currentLine here
// Now we'll make sure we process the line we've just read on the
// next iteration - so long as it wasn't the last line
currentLine = nextLine;
}
Upvotes: 3
Reputation: 75356
Subclass it and override the readLine() method to do as you want.
Upvotes: 2