简体   繁体   English

Java扫描器hasNextLine返回false

[英]Java Scanner hasNextLine returning false

This is probably due more to my lack of familiarity with the code than anything else, but I keep having the following problem: 这可能是由于我对代码缺乏了解而不是其他原因造成的,但是我仍然遇到以下问题:

I have a text file that has empty lines, and a scanner that goes through the file. 我有一个带有空行的文本文件,以及一个扫描该文件的扫描仪。

When I use the .hasNextLine() method, it returns false even though there are more lines in the file. 当我使用.hasNextLine()方法时,即使文件中有更多行,它也会返回false。 I must point out that the file begins with an empty line, and that the text inside has more empty lines in between, and finally ends with empty lines. 我必须指出,该文件以空行开头,并且内部文本之间有更多空行,最后以空行结束。

But shouldn't it return true regardless of whether the lines have text or not? 但是,无论行中是否有文本,它是否都不应返回true?

Yes, it should. 是的,应该。

Try this: 尝试这个:

public static void main(String[] args){
    Test t = new Test();
    t.testHNL(new File("test.txt"));
}

public void testHNL(File f){
    try {
        Scanner s = new Scanner(new FileInputStream(f));
        while(s.hasNextLine()){
            System.out.println("There is another line!  :: "+s.nextLine());
        }
        System.out.println("There are no more lines :'(");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Make sure the file "text.txt" exists, and just carriage returns in it. 确保文件“ text.txt”存在,并且回车。 Then run this. 然后运行这个。

use the .hasNext() method instead of using the .hasNextLine() method. 使用.hasNext()方法,而不是使用.hasNextLine()方法。 You are having problems because the .hasNextLine() method returns true only if the next line has some content in it. 您遇到了问题,因为.hasNextLine()方法仅在下一行包含某些内容时才返回true。 Whereas the .hasNext() method returns true even if there is any token in the next line(here the token being \\n for the next line) 即使下一行中有任何标记, .hasNext()方法也会返回true(此处,下一行的标记为\\n

Taken from the source for SUNs (oracles?) 1.5 JDK, anything which matches the following regular expression is treated as a "line". 取自SUN(oracles)1.5 JDK的源代码,与以下正则表达式匹配的任何内容均被视为“行”。 This includes empty lines under Windows or linux/unix. 这包括Windows或linux / unix下的空行。

private static final String LINE_SEPARATOR_PATTERN = 
    "\r\n|[\n\r\u2028\u2029\u0085]"

So it should return true even if lines are empty except for carriage return. 因此,即使回车以外的行为空,也应返回true。

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

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