How to take the name of the elements of a folder in an orderly way JFileChooser

0

I'm doing a program which can choose a folder with JFileChooser and that in the console shows the name of the files in the folder in an orderly way.

JFileChooser selecto = (JFileChooser) e.getSource();
    String comand = e.getActionCommand();
    if (comand.equals(JFileChooser.APPROVE_SELECTION)) {

        File rutaActual = selecto.getSelectedFile();
        File[] archivos = rutaActual.listFiles();
        JOptionPane.showMessageDialog(this, "Archivos de la carpeta "+rutaActual.getName()+" renombrados exitosamente ");

        String nombreCarpeta = rutaActual.getName();
        this.transformar = new Transformador();

        for (int i = 0; i < archivos.length; i++) {


            System.out.println(archivos[i].getName()+"\n");
        }

    }

But it turns out that it appears inconsistent in certain cases, such as choosing a folder that contains 12 files with the names of each file, equal to the corresponding place, this shows on screen: (1, 10, 11, 12 , 2, 3, 4, 5, 6, 7, 8, 9) that way I do not know what I could fix in my code to solve my problem.

Any help will be welcome.

    
asked by Getsuga Tenshou 12.01.2018 в 00:55
source

1 answer

0

For that you have to sort the list. First you have to convert the Array to List to be able to sort it, to convert an Array to List use the asList () method of the Arrays class. Then you use the sort () method of the Collections class to sort the list.

Convert the Array to List.

List<File> listaArchivos = Arrays.asList(archivos);

Sort the list using the names of the files.

Collections.sort(listaArchivos, new Comparator<File>() {
    @Override
    public int compare(File o1, File o2) {
        return o1.getName().compareTo(o2.getName());
    }
});

Print the list

for (File archivo : listaArchivos) {
    System.out.println(archivo.getName());
}

At the end the code would look like this:

...

if (...) {

    File rutaActual = selecto.getSelectedFile();
    File[] archivos = rutaActual.listFiles();
    JOptionPane.showMessageDialog(this, "Archivos de la carpeta "+rutaActual.getName()+" renombrados exitosamente ");

    String nombreCarpeta = rutaActual.getName();
    this.transformar = new Transformador();

    List<File> listaArchivos = Arrays.asList(archivos);

    Collections.sort(listaArchivos, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    for (File archivo : listaArchivos) {
        System.out.println(archivo.getName());
    }
}
    
answered by 12.01.2018 в 14:26