Read a TXT file, sort, and save a new Java file

0

I am doing a job for college, and I am not able to read the file and play the data inside an ArrayList to sort the data, my code so far

public class Teste {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException {
    ArrayList<String> vet = new ArrayList<>();
    String aux = null;
    int i = 0;
    vet.add("nome");
    vet.add("cidade");
    vet.add("estado");
    vet.add("aula");
    vet.add("cifra");


      BufferedReader lerArq = new BufferedReader(new FileReader("Teste.txt"));
      String s;
      int n = 0;
      try{
          while ((s = lerArq.readLine()) != null){
              n++;
          }
          System.out.println(s);
      }
   catch(Exception e){
       System.out.println("Excecao1\n");
   }

    System.out.println("Vetor desordenado: ");
    for (i = 0; i < 5; i++) {
        System.out.println(" " + vet.get(i));
    }
    System.out.println(" ");
    for (i = 0; i < vet.size(); i++) {
        for (int j = 0; j < vet.size()-1; j++) {
            if (vet.get(j).compareToIgnoreCase(vet.get(j + 1)) > 0) {
                aux = vet.get(j);
                vet.set(j, vet.get(j + 1));
                vet.set(j + 1, aux);
            }
        }
    }
    System.out.println("Vetor organizado:");
    for (i = 0; i < vet.size(); i++) {
        System.out.println(" " + vet.get(i));

    }
    int x = 1;
     System.out.println(vet.get(x-1));
}
}

The ordering is working, I just can not use FileReader , any hint how to throw the data into the ArrayList ?

Remembering, the data contained in the txt is the same as the one below, 5 words, each in a new line.

    vet.add("nome");
    vet.add("cidade");
    vet.add("estado");
    vet.add("aula");
    vet.add("cifra");
    
asked by anonymous 19.11.2014 / 15:13

1 answer

1

If the words have been one in each line, you can use this code:

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
        String line = br.readLine();

        while (line != null) {
            vet.add(line);
            line = br.readLine();
        }
    }
    
19.11.2014 / 15:20