Reputation: 469
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
Upvotes: 4
Views: 7287
Reputation: 51
I resolved it using new Scanner(new BufferedReader(new FileReader(fileName)))
instead of new Scanner(new File(fileName))
Upvotes: 5
Reputation: 14761
it maybe occurred for this problems:
1-your file maybe isn't created.
2-your file is in use for other programs.
3-the path address is false.
Upvotes: 0
Reputation: 469
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.
Upvotes: 3
Reputation: 2633
EDIT: Fisrt guess was wrong
The file might have 1400 lines full of whitespaces.
Upvotes: 0