Scanner No Line Found Exception

假装没事ソ 提交于 2019-11-30 10:01:19

问题


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?



来源:https://stackoverflow.com/questions/7688710/scanner-no-line-found-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!