1

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.

Community
  • 1
  • 1
user25976
  • 1,005
  • 4
  • 18
  • 39

1 Answers1

2

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.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • This looks good. If i'm understanding correctly, the reader doesn't actually read or contain the parameters, text, etc. Only a reference to the object? I'm going to try this... – user25976 Mar 08 '16 at 22:46
  • @user25976: the reader just reads a line. Then you break the line into its constituent parts, create a viable object with it and add it to your List. – Hovercraft Full Of Eels Mar 08 '16 at 23:33