Ad

How To Use Scanner To Read Accented Characters From File In Correct Way?

- 1 answer

I have this method:

 public static void readFile(String input)
    throws FileNotFoundException, IOException{
        try (Scanner sc = new Scanner(new File(input));){

            while (sc.hasNextLine()){
                String currentLine = sc.nextLine();
                if(sc.hasNextLine()){
                    String nextLine = sc.nextLine();

                    System.out.println("currentLine\t"+currentLine);
                    System.out.println("nextLine\t"+nextLine);
                }
            }
         }
    }

It works correctly, without any errors, or any problems, but this not write any content from the file. In the file I have some basic "lorem ipsum" text, just to see how this works. If in the file only latin characters are then this works correctly, but if is there any other characters (ex: áéűőúüöó) then this not write any content from the file. Where can I have the problem? How can I resolve this?

Ad

Answer

You probably have just single line and the bug is here:

            while (sc.hasNextLine()){
                String currentLine = sc.nextLine();
                if(sc.hasNextLine()){

you get the current line but print it only when there is next line. In this way last line will be missing.

Please remove the IF condition.

EDIT: After question editing please try to give proper encoding ex for UTF8:

new Scanner(new File(fileName), StandardCharsets.UTF_8.name());
Ad
source: stackoverflow.com
Ad