Scanner.hasNext() returns false

删除回忆录丶 提交于 2019-12-07 08:58:31

问题


I have directory with many files in it - each with over 800 lines in it. Hovewer, when I try to read it using Scanner, it seems empty.

File f1 = new File("data/cityDistances/a.txt"),
     f2 = new File("data/cityDistances/b.txt");
System.out.println(f1.exists() && f2.exists()); //return true
System.out.println(f1.getTotalSpace() > 0 && f2.getTotalSpace() > 0); //return true
Scanner in = new Scanner(f1);
System.out.println(in.hasNext()); // return false;
System.out.println(in.hasNextLine()); //return false;

Why can it behave like that?


I've managed to do it using BufferedReader. Nonetheless, it seems even more strange that BufferedReader works and Scanner didn't.


回答1:


As the default delimeter for Scanner is whitespace, that would imply your a.txt contains only whitespace - does it have 800 lines of whitespace? ;)

Have you tried the following?

new Scanner(new BufferedReader(new FileReader("a.txt")));



回答2:


I had a similar problem today reading a file with Scanner. I specified the encoding type of the file and it solved the problem.

scan = new Scanner(selectedFile,"ISO-8859-1");



回答3:


This also happened to me today. I'm reading a plain text file from a Linux system written by some application in a Windows box and Scanner.hasNextLine() is always false even tough there are lines with the Windows line separator and all. As said by Hound Dog, by using

Scanner scanner = new Scanner(new BufferedReader(new FileReader(file))); 

it worked like a charm. FileReader or BufferedReader seem to properly identify and use some file characteristics.




回答4:


Checking the scanner's exception may show that the file can't be read.

...
System.out.println(in.hasNext()); // return false;
IOException ex = in.ioException();
if (ex != null)
  ex.printStackTrace(System.out);
...



回答5:


The function File.getTotalSpace() is not behaving how you're expecting. It is returning the size of the partition where those particular files are located.

You want to use File.length().




回答6:


refer to file address you are using linux, refer to your name there is possible some Polish or Czech character and refer to below link, scanner dont like non utf-8 characters on linux:)

http://karussell.wordpress.com/2008/09/04/encoding-issues-solutions-for-linux-and-within-java-apps/




回答7:


This probably doesn't answer the OP's question, but for anyone else who is experiencing "my iterator's hasNext() is always false!"--if you have a bunch of watches with .next() in them, your IDE or whatever is actually advancing the cursor position per each one. This has caused me much trouble. Be careful with iterators and watches.



来源:https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!