List of files in a folder [closed]

-3

Hello I'm using JFileChooser to get files on the system.

But now I need to use JFileChooser to select folders and add all of their content to the program. I used DIRECTORIES_ONLY and it worked. Now I want to add all the files (using a filename of file (mp3)) in an arrayList and show to the user. However, I've been around a lot of the internet, and the codes I'm using do not work. Could someone help me?

I need to use JFileChooser, not .walk

Currently, I'm trying to do it like this:

adicionarPasta.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser chooser = new JFileChooser();
            chooser.showOpenDialog(parent);
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
            String diretorio = chooser.getAbsolutePath();//essa linha está com erro
            // TODO Auto-generated method stub
            File file = new File(diretorio);
            File afile[] = file.listFiles();
            int i = 0;
            for (int j = afile.length; i < j; i++) {
                File arquivos = afile[i];
                System.out.println(arquivos.getName());
            }
        }
    });
    
asked by anonymous 24.11.2016 / 20:56

2 answers

2

Using Java 8

If you want to return the objects File :

private ArrayList<File> listar(String caminho, String extensao) {
  File pasta = new File(caminho);

  return this.listar(pasta, extensao);
}

private ArrayList<File> listar(File pasta, String extensao) {
  ArrayList<File> arquivos;

  arquivos = new ArrayList<>(Arrays.asList(pasta.listFiles()));
  arquivos.removeIf(arquivo -> !arquivo.getName().endsWith(extensao));

  return arquivos;
}

The usage would be as follows:

final JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showOpenDialog(null);

System.out.println(this.listar(chooser.getSelectedFile(), ".mp3"));
    
24.11.2016 / 21:20
0

The getSelectedFiles method of javax.swing.JFileChooser returns a File []. You can use it to return an array of File objects, after enabling multiple selection with setMultiSelectionEnabled . If you do not enable multiple selection, you will not be able to select multiple files at once, and return them all with getSelectecdFiles.

    
24.11.2016 / 21:39