扫描仪未发现线路异常
我收到以下异常。
java.util.NoSuchElementException: No line found
我在编写需要从文本文件中读取的较大程序时遇到此错误,因此决定进行测试。
Scanner scan = new Scanner(new File("restrictions.txt");
String s1 = scan.nextLine();
System.out.println(s1);
我仍然得到例外。我在与名为“restrictions.txt”的类相同的文件夹中有一个文本文件,其中包含文本。我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
new File("restrictions.txt") 将在应用程序的“启动目录”中查找文件 - 如果您使用的是 Eclipse,它可能是项目的根目录。
要打开您的类旁边的文件,您可以使用 Scanner 构造函数,它接受您获得的 InputStream
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
您应该在调用
in.nextLine()
之前使用if(in.hasNextLine())
。否则对于最后一行,它将抛出 Line not found 异常。You should use
if(in.hasNextLine())
before callingin.nextLine()
. Otherwise for last line it will thrown Line not found exception.的 Javadoc
扫描仪 需要指定行结尾以便它知道行是什么?
Javadoc for Scanner
Do you need to specify a line ending so it knows what a line is?