简体   繁体   English

Java扫描器无法读取文件

[英]Java Scanner unable to read file

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. 扫描程序将文件(大约1400行长)视为空文件。

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 我怀疑该文件是从Windows机器导入到Linux机器的事实,但我的想法是其他可能性

edited for formatting and code errors 编辑格式和代码错误

我使用new Scanner(new BufferedReader(new FileReader(fileName)))而不是new Scanner(new File(fileName))

Found the problem: Looked at the file byte by byte. 发现问题:逐字节查看文件。 found an EOF character in the first byte. 在第一个字节中找到一个EOF字符。 Java was ignoring the rest of the file. Java忽略了文件的其余部分。

EDIT: Fisrt guess was wrong 编辑:Fisrt猜测是错误的

The file might have 1400 lines full of whitespaces. 该文件可能有1400行空白。

it maybe occurred for this problems: 可能是因为以下问题:

1-your file maybe isn't created. 1-您的文件可能未创建。

2-your file is in use for other programs. 2-您的文件正在用于其他程序。

3-the path address is false. 3-路径地址为假。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM