Scanner No Line Found Exception

2019-01-29 11:05发布

问题:

I am getting the following exception.

java.util.NoSuchElementException: No line found

I got this error while writing a larger program which needed to read from a text file, and so decided to do a test.

Scanner scan = new Scanner(new File("restrictions.txt");
String s1 = scan.nextLine();
System.out.println(s1);

And I still get the exception. I have a text file in the same folder as the class called restrictions.txt which has text in it. What am I doing wrong?

回答1:

new File("restrictions.txt") will look for the file in the "Start dir" of your app - if you're using Eclipse, it's probably the root of your project.

To open the file next to your class, you can use the Scanner constructor which accepts an InputStream that you get by

YourClass.class.getResourceAsStream("restrictions.txt")


回答2:

You should use if(in.hasNextLine()) before calling in.nextLine(). Otherwise for last line it will thrown Line not found exception.



回答3:

Javadoc for Scanner

Do you need to specify a line ending so it knows what a line is?