Special Character with Scanner and Filereader

Asked

Viewed 58 times

1

I have a.txt file with the following values:

TESTE
17,00%
01/01/2014
25,55
AÇAILANDIA

When importing this txt in my Java application the special character Ç is not imported and the result is like this:

TESTE
17,00%
01/01/2014
25,55
A�AILANDIA

Below is the method I use to import the file:

private void lerArquivo4() throws FileNotFoundException {
        //https://blog.caelum.com.br/lendo-arquivos-texto-em-java/
        Scanner scanner = new Scanner(new FileReader("C:/Users/jallisson/Desktop/testejj.txt")).useDelimiter("\\||\\n");
        while (scanner.hasNext()) {
            String numero = scanner.next();
            String matricula = scanner.next();
            String materia = scanner.next();
            String prova = scanner.next();
            String nota = scanner.next();
            System.out.println(numero);
            System.out.println(matricula);
            System.out.println(materia);
            System.out.println(prova);
            System.out.println(nota);
            JOptionPane.showMessageDialog(this, nota, "Linha", JOptionPane.INFORMATION_MESSAGE);

        }
    }

1 answer

1


The problem is at the time of reading the file.

How are you using just the Filereader, default charset will be assumed (in case your JVM should be ISO-8859-1, can be easily checked through Charset.defaultCharset())

Citing the excerpt from the documentation:

The constructors of this class assume that the default Character encoding and the default byte-buffer size are appropriate.

We can then read the file setting the charset to UTF-8:

Scanner scanner = new Scanner(new InputStreamReader(
    new FileInputStream("C:/Users/jallisson/Desktop/testejj.txt"), Charset.forName("UTF-8")))
            .useDelimiter("\\||\\n");

The output will be as expected:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.