扫描仪没有发现线路exception
我收到以下exception。
java.util.NoSuchElementException:找不到行
我在编写需要从文本文件中读取的较大程序时遇到此错误,因此决定进行测试。
Scanner scan = new Scanner(new File("restrictions.txt"); String s1 = scan.nextLine(); System.out.println(s1);
我仍然得到例外。 我在一个名为restrictions.txt的类的文件夹中有一个文本文件,其中包含文本。 我究竟做错了什么?
新文件(“restrictions.txt”)将在您的应用程序的“开始目录”中查找该文件 – 如果您使用的是Eclipse,它可能是您项目的根目录。
要打开类旁边的文件,可以使用Scanner构造函数,该构造函数接受您获得的InputStream
YourClass.class.getResourceAsStream("restrictions.txt")
你应该在调用in.nextLine()
之前使用if(in.hasNextLine())
in.nextLine()
。 否则对于最后一行,它将抛出Line not foundexception。
Javadoc for Scanner
你需要指定一个行结尾,以便知道一行是什么吗?