Listing files from a folder

Asked

Viewed 1,035 times

-2

Hello I am using Jfilechooser to pick up files on the system.

Only now I need to use Jfilechooser to select folders and add all their contents in the program. I used DIRECTORIES_ONLY and it worked. Now I want to add all the files (through a file type filto (mp3)) in an arrayList and show to the user. But I’ve already searched a lot of the internet and the codes I find as a base do not serve/do not work. Could someone help me?

I need to use Jfilechooser, not . walk

Currently, I’m trying to do it this way:

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());
            }
        }
    });

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 use 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"));
  • The person who downvoted can say what’s wrong so I can correct the answer?

0

  • It is, but I don’t want the user to add more than one file manually. What I want is a "add complete folder" with files. mp3 is a file arraylist

  • You can use the new file("Folder/path"). listFiles() :p It also returns a File[]. Just take the path of the selected folder with Jfilechooser, and iterate over the listFiles() to pass them to an Arraylist or whatever.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.