Reading of text file

Asked

Viewed 229 times

1

I need to handle 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 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 do to read the file without corrupting it?

  • 1

    I did exactly what you did and the result came out perfect. It doesn’t seem to be code problem. Tried to make some change?

  • Thinking it may be a problem in another method that serves to check whether the file is empty or not

  • in this method I use File = new File("data/data.txt"); only

  • @Roney If possible post the code of this method.

1 answer

1

Check the encoding you’re using. The problems that occur with corrupted files are often related to the encoding used for reading the file. Look at the following post and make the indicated change: https://stackoverflow.com/questions/12096844/how-to-read-a-file-in-java-with-specific-character-encoding.

So 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 the UTF8 charset if you are using another encoding in your application.

  • Although the link is from Soen, it is recommended that you add an example here, so that the link is only for reference and query.

  • Got it. I’ll put it then! Thank you ^^

Browser other questions tagged

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