• Post Reply Bookmark Topic Watch Topic
  • New Topic

Read text file lines in a specific order  RSS feed

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

Can anyone help me on the best method to use to read file lines in a specified order. For example, say I have a text file with 10 lines but I want them read in the order 8-3-1-2-4-9-10-7-6-5 then what is the best way of doing this rather than having to open and close the file 10 times to get to the line I want to process each time?!? Note that the file is too big to read into memory...

Thanks.

Sam
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you need this? What have you tried?
Hint 1: BufferedReader has a method readLine.
Hint 2: Sort the line numbers.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do you need to read all of them eventually, or just a subset? If the latter, can you read the file sequentially, and just save the lines you need as you reach them, and then process those in the required order?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sam Bluesman wrote:Note that the file is too big to read into memory...

10 lines?

Sounds like one of those Euler puzzles to me.

I think if I was going to tackle it exactly as written, I'd do as Fred suggested and try reading in as much as I can in a way that maximizes my chances.

For example, if I have a file with ten lines but I'm only allowed to read in 5 at a time:

Round 1: look at 8; the next line (3) is beyond the spread that we could store in 5 slots, so process line 8 only.
Round 2: look at 3 and keep going until the "spread" of lines to be read exceeds 5 - ie, 3, 1, 2, 4, 9 - so read the first four lines in and process them in the required order.
Round 3: look at 9 and keep going until the spread of lines to be read exceeds 5 - ie, 9, 10, 7, 6, 5 - so read in lines 6-10 and process them in the required order.
Round 4: the last line is 5, so read it in and process it.

And I'm quite sure there are MANY other possibilities (and very likely better ones). But that's where I'd start.

Of course, this assumes that the problem is theoretical, and you're NOT allowed to sort, as Pawel suggested.

Winston
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!