javajava.util.scannernosuchelementexception

exception in thread main java.util.nosuchelementexception with new Scanner(file)


I have a problem with my code,I get this error all the time:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at audio.AudioSecrets.main(AudioSecrets.java:32)
Java Result: 1

my problem is this ligne:

contents = new Scanner(file).useDelimiter("\\Z").next().toCharArray(); // 

The \\Z delimiter in combination with .next() will read input until there isn't any left.

how can I input the file to my program,thanks for help


Solution

  • You should check hasNext() before calling next(). Probably there are no elements matching your criteria.

    Scanner s = new Scanner(file);
    s.useDelimiter("\\Z");
    if(s.hasNext()) {
       contents = s.next().toCharArray();
    }