Question

I have problem with my CODE. IF I add words with accent mark to file, Scanner won´t read it.Thank you for help.

For example if file "names.txt" contains: John Lil None

number of words in file is 3

but if contains: Jóhn Lil None

number of words in file is 0

CODE IS:

    File file=new File("names.txt");
    Scanner skener=new Scanner(file);


    int count=0;

    while(skener.hasNext()){

        aArrayListOfNames.add(skener.next());
        count++;
    }

    skener.close();
    System.out.println("Count is "+count);
    return count;

Thank you all, problem FIXED! :D

Was it helpful?

Solution

Construct the Scanner by defining the charset it should use:

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

I believe ASCII is the default charset for Scanner so that needs to be changed. Also the file might not be encoded in UTF-8.

OTHER TIPS

I tried to get your error but it worked for me...

private static void getStrings() throws FileNotFoundException {
    List<String> nameArray = new ArrayList<String>();
    File file = new File("C:\\Users\\XXX\\workspace\\stackoverflowtest1\\src\\stackoverflowtest1\\names.txt");
    Scanner scanner= new Scanner(file);

    int count = 0;

    while (scanner.hasNext()) {

        nameArray.add(scanner.next());
        count++;
    }

    scanner.close();
    System.out.println("Count is " + count);
    System.out.println("1 - " + nameArray.get(0));
    System.out.println("2 - " + nameArray.get(1));
    System.out.println("3 - " + nameArray.get(2));
}

OUTPUT:

Count is 3
1 - Jóhn
2 - Lil
3 - None
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top