What is the problem with Scanner hasNext() method? When hasNext() method read empty txt file and get false, after i write something to file and recheck with hasNext() but this time it again returns false. But when i remove if(hasNext()) block it works fine. I suspect that problem occurs due to s.hasNext() method. Is there bug in Scanner class?
public static void main(String[] args) throws Exception {
File file= new File("file.txt");
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
FileReader fr = new FileReader(file);
Scanner s = new Scanner(fr);
if (s.hasNext()) { // RETURNS FALSE GOES TO ELSE OK(because file is empty)
//doSomething();
} else{
pw.println(1); // WRITE SOMETHING TO FILE
pw.close();
System.out.println(s.hasNext()); // returns FALSE AGAIN
int num = s.nextInt();
System.out.println("LOOP: " + num + " ***");
s.close();
}
}