Disorder words from a txt

0

I have a program made in JAVA that shows in console a txt file that contains a list of words sorted alphabetically:

try{
  FileReader fr = new FileReader("archivo.txt");
  BufferedReader br = new BufferedReader(fr);
  String [] file = {"archivo.txt"};
  ArrayList<String> fileList =new ArrayList<String>(Arrays.asList(file));    
  String cadena;
  while((cadena=br.readLine())!=null){
     System.out.println(""+cadena);
   }
  }catch(Exception e){ }
 }
}

I need that when you save them in a ArrayList you mess up, and show them like this in console. I tried with:

Collections.shuffle(arrayList);

And nothing, what do you suggest?

    
asked by Mario 06.06.2017 в 08:44
source

1 answer

3

In Effect the method shuffle is used to randomly clutter the elements of a List, Entering already in its code, recommend using try-with-resources , you are also trying to change the order incorrectly, since the array will have only a String that will be the name of the file. (taking into account that in the example instead of arraylist as a shuffle parameter you referred to fileList created)

To have the elements in the list, you must add the element to the ArrayList previously created within the while .

Possible final code

public static void main (String args []) throws IOException{
  String line = "";
  ArrayList<String> fileList = new ArrayList<>();
  try (BufferedReader br = new BufferedReader(new FileReader("archivo.txt"))) {
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        fileList.add(line); /* Agregamos la Línea leída a la lista */
      }
 }
  System.out.println("LISTA DESORDENADA ");
  Collections.shuffle(fileList); /* Modificar Orden*/
  /* Imprimir en una sola línea , puede optar por un ciclo */
  System.out.println(fileList.toString()); 
}
    
answered by 06.06.2017 / 09:24
source