-2

I am trying to write a java program to parse relevant strings from a .txt file with a certain format. I want to use the contents of the .txt file to initiate data for my classes. A sample file would look like this:

Movies
Lord of the Rings: 180
Fight Club: 120
...
Theaters
A:100
B:50
C:200
...
Shows
1,1,960
1,1,1080
1,1,1200
1,3,1020
1,3,1140
2,2,990
2,2,1210
...
Prices
Adult:10
Child:7
Senior:8
...
End

This is what I have so far (and it is returning an error when trying to read the above file to initialize my class.

public static void inititializeFromFile(String fileName) throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    while((line = reader.readLine()) != null) {

        if(line.equals("Movies")) {
            while (!(line.equals("Theaters"))) {
                String currentline = line;
                String[] parts = currentline.split(":");
                String part1 = parts[0]; 
                String part2 = parts[1]; 
                movies.add(new Movie(part1, part2));
            }
        }
        // do basic string comparisons here
        if(line.equals("...")) {
            // do something
        }
        else if(line.contains(":")) {
            // most likely of type A:100, B:50
        }
        else if(line.equals("End")) {
            // do something
        }
        else {
            // anything else
        }
    }
    reader.close();
}

}

b33k3rz
  • 173
  • 1
  • 8

1 Answers1

1

Here is a sample program that will read in the file for you, line by line, and has some scenarios to determine what type of line we are looking at. I was lazy and threw the IOExceptions that might be thrown at me in the code - you should never do this, instead modify the program to use a try catch.

import java.io.*;

public class tmp {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("file.txt"));
        String line;

        while((line = br.readLine()) != null) {
            // do basic string comparisons here
            if(line.equals("...")) {
                // do something
            }
            else if(line.contains(":")) {
                // most likely of type A:100, B:50
            }
            else if(line.equals("End")) {
                // do something
            }
            else {
                // anything else
            }
        }
        br.close();
    }
}
Vineet Kosaraju
  • 5,572
  • 2
  • 19
  • 21