Java 扫描仪无法读取文件
我正在做一个非常简单的文本解析程序,使用朋友给我的文件。 但是,当我使用像这样的扫描仪打开文件时,
Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
System.err.println(scan.nextLine());
System.err.println(scan.next());
结果是:
false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
扫描仪将文件(大约 1400 行长)视为空文件。
谁能想到扫描仪无法查看文件的任何原因吗?我怀疑该文件是从 Windows 计算机导入到 Linux 计算机的事实可能与此有关,但我对
针对格式和代码错误进行编辑的其他可能性持开放态度
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,
Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
System.err.println(scan.nextLine());
System.err.println(scan.next());
result:
false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
the scanner treats the file(which is some 1400 lines long) as empty.
Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities
edited for formatting and code errors
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我使用
new Scanner(new BufferedReader(new FileReader(fileName))) 解决了它,而不是
new Scanner(new File(fileName))
I resolved it using
new Scanner(new BufferedReader(new FileReader(fileName)))
instead ofnew Scanner(new File(fileName))
发现问题:
逐字节查看文件。在第一个字节中发现 EOF 字符。
Java 忽略了文件的其余部分。
Found the problem:
Looked at the file byte by byte. found an EOF character in the first byte.
Java was ignoring the rest of the file.
编辑:第一次猜测是错误的
该文件可能有 1400 行充满空格。
EDIT: Fisrt guess was wrong
The file might have 1400 lines full of whitespaces.
可能是因为这个问题而发生的:
it maybe occurred for this problems: