Read file and save lines

Asked

Viewed 936 times

3

I want to read a txt file recording each line of the file in variables of type String, (I use to save some data, of a basic program that I am doing) I thought of something like this

    try {
        FileReader fr = new FileReader("C:\\Users\\lucas\\Desktop\\teste.txt");
        BufferedReader br = new BufferedReader (fr);
         String linha1 = br.readLine();// Uma da variaveis 
         // String linha2 = (?) // Como pego a segunda linha do txt e salvo aqui ?
         // String linha3 = (?) 
         while (linha != null){
             SetFirst(linha);// Funcao do objeto o qual estao os dados guardados
             linha=br.readLine();



         }
        System.out.println("Exiting...");
        br.close();
        fr.close();


    } catch (Exception e) {
       JOptionPane.showMessageDialog(null,e.getMessage());
    }
  • And who doubts about the code?

  • I would like to know how to store the other lines of the text file in different variables, if possible.

  • 1

    List<String> linhas = Files.readAllLines(Paths.get("meuarquivo.txt"));

  • Jeez, very complex, but vlw

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

5

One of the possible ways is by using ArrayList and storing each line in an index:

   try {

        FileReader fr = new FileReader("C:\\Users\\lucas\\Desktop\\teste.txt");
        BufferedReader br = new BufferedReader (fr);
        ArrayList<String> linhas = new ArrayList<>();
        String linha = ""; 

         while ((linha=br.readLine()) != null){

             SetFirst(linha);// Funcao do objeto o qual estao os dados guardados
             linhas.add(linha);

         }
        System.out.println("Exiting...");
        br.close();
        fr.close();


    } catch (Exception e) {
       JOptionPane.showMessageDialog(null,e.getMessage());
    }

1

If using Java 8:

List<String> linhas = new ArrayList<>();
String caminho = "C:/Users/lucas/Desktop/teste.txt";

try (Stream<String> stream = Files.lines(Paths.get(caminho))) {
  stream.forEach(linhas::add);
} catch (IOException e) {
  JOptionPane.showMessageDialog(null, e.getMessage());
}

//linhas.forEach(System.out::println);

Browser other questions tagged

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