Reading a text file

1

I need to deal with a 3-line file with the following structure:

nome
data
horário

To read this method I use the following commands:

BufferedReader leitor = new BufferedReader(new  FileReader("dados/dados.txt"));
ArrayList<String> dados = new ArrayList<>();

String linha = "";

while((linha = leitor.readLine()) != null){
    dados.add(linha);
}

leitor.close();

But at the end of the reading, the first line of the file gets corrupted with the value null , when in fact it was to continue with the value of the name field.

How can I read the file without corrupting it?

    
asked by anonymous 23.08.2016 / 17:24

1 answer

1

Check the encoding you are using. Problems that occur with corrupted files are often related to the encoding used to read the file. Look at the following post and make the change indicated: link .

Then in your case it would look like this:

String fileName = "dados/dados.txt";
FileInputStream is = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-8"));
BufferedReader leitor = new BufferedReader(isr);
ArrayList<String> dados = new ArrayList<>();

String linha = "";

while((linha = leitor.readLine()) != null){
  dados.add(linha);
}

leitor.close();

Switch UTF8 charset if you are using another encoding in your application.

    
29.08.2016 / 13:41