user25976
user25976

Reputation: 1035

Java buffered reader - jump to line

I'm reading through a file like this:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = fileChooser.showOpenDialog(this);

if (result == JFileChooser.CANCEL_OPTION) {
    System.exit(1);
}

file = fileChooser.getSelectedFile();

java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(file));
String line = reader.readLine();
while (line != null) {
//do stuff for each line
}
reader.close();

The file looks like this:

0 LOAD 1,3 
1 LOAD 0,2
2 ADD 1,2
3 ADD 0,1
4 LSS 1,3,2
5 STOR 62,1

I've parsed it like this:

String[] actionFirstSplit = line.split(" ");

There's code associated with each line that isn't shown here. For certain lines, I'd like to jump back to a certain line number, and continue reading through the file once again. What is the best way to do this? Do I have to create another reader and skip lines until the particular line I'm interested in? I'm looking along the lines of this post, but I want to continue reading the rest of the file.

Upvotes: 1

Views: 1111

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

If this were my project, I'd

  • Create a class, perhaps called MyClass (for discussion purposes only), to hold one line's worth of data. It would have line number, String for text (command?), and a List<Integer> to hold a variable number of int parameters.
  • Create a List<MyClass> to hold a linear collection of objects of this class.
  • In my single BufferedReader, read each line, create a MyClass object, and place it in the collection.
  • When I needed to loop back, I simply search through my collection -- no need to re-read from a file since this is a relatively expensive task while looping through a List such as an ArrayList isn't quite so.

Upvotes: 2

Related Questions