Nikhil Das Nomula
Nikhil Das Nomula

Reputation: 1953

Determine Line Number from Byte Offset in a text file

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

Answers (2)

Michael Shopsin
Michael Shopsin

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

lynks
lynks

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

Related Questions