lasvega
lasvega

Reputation: 13

Reading Text File into Array using Java generates Exception

Even though the file Movie_db.txt isn't empty, I get the following exception:

the text file consists of this:

hank horror 20.0 18 1

public void syncDB(List<Movie> movieList) throws IOException {
  Scanner scanner = new Scanner("Movie_db.txt");
  BufferedReader reader = null;
  try {
      String line = null;
      String title;
      String genre;
      double movieDuration;
      int ageRestriction;
      int id;
      while (scanner.hasNext()) {
          title = scanner.next();
          genre = scanner.next();
          movieDuration = scanner.nextDouble();
          ageRestriction = scanner.nextInt();
          id = scanner.nextInt();
          movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
      }
  } catch (Exception e) {
      System.out.println("List is empty");
  }
}

Upvotes: 0

Views: 80

Answers (2)

Ashvin Sharma
Ashvin Sharma

Reputation: 583

Considering your path is correct, there is a problem in your code. I'd change this line

    Scanner scan = new Scanner("Movie_db.txt");

with this one

    Scanner scan = new Scanner(Paths.get("Movie_db.txt"));

The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.

Read Scanner documentation for more info

Upvotes: 2

Vinay Prajapati
Vinay Prajapati

Reputation: 7505

genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.

You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.

Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));

Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.

Upvotes: -1

Related Questions