Java scanner hasNextLine returns false

I have several files (in fact they are also java source files saved in Eclipse on Ubuntu) that I need to read and process line by line. I noticed that I cannot read one of the files. The code I am using is below

try (Scanner scanner = new Scanner(file)) {
    while (scanner.hasNextLine() ) {
        builder.append(scanner.nextLine()).append("\n");
    }
} catch (FileNotFoundException ex) {
    System.out.println("Error");
}

      

I checked beforehand if the file exists. And so it is. I can even rename it. But I cannot read a single line. hasNextLine just returns false. (I even try hasNext).

At the end I go through the contents of the file and find that there is another view (which was in the comments section of the java file). This is the next character.

¸

      

When I remove this character, I can read the file normally. However, this is not acceptable. What can I do to read files even with this character?

+3


source to share


1 answer


This is most likely a character set issue caused by a different set by default on the platform your Java code is running on; it's always a good idea to specify the expected / required character set to be used when parsing, and with the Scanner class it's just a call to the as constructor:

Scanner scanner = new Scanner(file, "UTF-8");

      



where the second parameter is an alphabetic character set or even better :

Scanner scanner = new Scanner(file, StandardCharsets.UTF_8);

      

+2


source







All Articles