Read file and save lines

3

I want to read a txt file by writing each line of the file into String variables, (which I use to save some data, from a basic program I'm 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());
    }
    
asked by anonymous 20.11.2016 / 18:29

2 answers

5

One of the possible ways is by using ArrayList and storing each row 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());
    }
    
20.11.2016 / 18:56
1

If you are 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);
    
24.11.2016 / 12:20