Reputation: 1953
I currently have a scenario where I know the byte offset of a text file. I want to know is there anyway in which I can determine the line number from the byte offset. The records in the text file are not of fixed length, in which case I would have divided the offset by the width.
Upvotes: 0
Views: 1799
Reputation: 2138
You cannot determine the line number from byte offset unless all the lines are a uniform length. However you can scan for newlines and keep track of them to calculate the offset in the file.
Upvotes: 3
Reputation: 5689
You could do something like;
String fullTextFile = loadTextFile();
String section = fullTextFile.substring(0, byteOffset);
String reduced = section.replaceAll("[^\n]*","");
int lineNumber = reduced.length();
I'm not entirely sure how legal that regex is, but it shouldn't require much tweaking.
Upvotes: 0