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. 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?
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. Then run this.
use the .hasNext() method instead of using the .hasNextLine() method.
You are having problems because the .hasNextLine() method returns true only if the next line has some content in it. 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With