0

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");
  }
}
9
  • please share the file content as well with exact name of the file. Commented Oct 1, 2019 at 8:40
  • The problem with your exception handling is that you print List is empty for any exception which might happen in your code. Use a debugger to find out the actual line which is causing the exception. Commented Oct 1, 2019 at 8:40
  • call e.printStackTrace() in the catch block. and update the output. Commented Oct 1, 2019 at 8:42
  • How are you so sure that if the code fails it will be because the "List is empty"? Commented Oct 1, 2019 at 8:44
  • @SandeepPolamuri Im getting these errors from stacktrace: java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextDouble(Scanner.java:2564) Commented Oct 1, 2019 at 8:46

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.