
Fastest way to read a certain line in a text file
Quote:
> I have a text file with around 31,000 lines of text.
> Is there a way to open the file and jump to (for example...) line 20,000
and
> get that single line's content and then close the file?
> Or is there a way to serialize the data in an arraylist or a custom
> structure and read only one record at a time?
> Each line in the file consists of a keyword and a description separated by
a
> "$".
> ex: "keyword$description"
> Any help would be greatly appreciated.
Unless the lines are a guaranteed fixed-length, the best way I know of to do
this would be to load the entire file and iterate through. This is why a lot
of flat data format files have fixed field sizes. If you have control over
the format and will be routinely using such large datasets, I'd highly
recommending changing it to use fixed field widths for your name-value
pairs. Then accessing a particular record becomes a matter of a trivial
offset calculation. For instance, 32 characters for the name, 64 for the
value. Then, to get to record n, you just open the file and jump to offset
(n-1) * (32 + 64). Gives you larger files to work with, but that's just the
tradeoff that you get.
Then again, I'm an old C/C++ guy; C# may implement some clever thing under
the hood for you that will do this; however, performance is likely to be
poor unless one of the two methods listed above is used.
- Steve