Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list files in a folder avoiding .DS_Store

Tags:

java

list

macos

When I try to list files in a folder with this:

String file;
File folder = new File("/Users/francesco/Desktop/VIDEOS");
File[] listOfFiles = folder.listFiles();
BufferedReader br = null;
for (int i = 0; i < listOfFiles.length; i++){

It reads also the .DS_Store file inside the folder, giving me a lot of errors. How can I avoid to read these .DS_Store files in Java?

like image 641
Hyperion Avatar asked May 27 '15 15:05

Hyperion


1 Answers

You can pass a FileNameFilter to File.listFiles to filter out the one you don't want.

    File[] files = folder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return !name.equals(".DS_Store");
        }
    });

EDIT: Java 8 lambda version

    File[] files = folder.listFiles((dir, name) -> !name.equals(".DS_Store"));
like image 91
MadConan Avatar answered Nov 02 '22 15:11

MadConan