How to loop through all the files in a folder (if the names of the files are unknown)?

17,494

Solution 1

Just use File.listFiles

final File file = new File("whatever");
for(final File child : file.listFiles()) {
    //do stuff
}

You can use the FileNameExtensionFilter to filter your files too

final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
    if(extensionFilter.accept(child)) {
        //do stuff
    }
}

Annoyingly FileNameExtensionFilter comes from the javax.swing package so cannot be used directly in the listFiles() api, it is still more convenient than implementing a file extension filter yourself.

Solution 2

So you can have more options, try the Java 7 NIO way of doing this

public static void main(String[] args) throws Exception {
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"))) {
        for (Path path : files) {
            System.out.println(path.toString());
        }
    }
}

You can also provide a filter for the paths in the form of a DirectoryStream.Filter implementation

public static void main(String[] args) throws Exception {
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"),
        new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return true; // or whatever you want
            }
        })
    ) {

        for (Path path : files) {
            System.out.println(path.toString());
        }
    }
}

Obviously you can extract the anonymous class to an actual class declaration.

Note that this solution cannot return null like the listFiles() solution.

For a recursive solution, check out the FileVisitor interface. For path matching, use the PathMatcher interface along with FileSystems and FileSystem. There are examples floating around Stackoverflow.

Solution 3

File.listFiles() gives you an array of files in a folder. You can then split the filenames to get the extension and check if it is .pdf.

File[] files = new File("C:\\Users\..myfolder").listFiles();
for (File file : files) {
    if (!file.isFile()) continue;

    String[] bits = file.getName().split(".");
    if (bits.length > 0 && bits[bits.length - 1].equalsIgnoreCase("pdf")) {
        // Do stuff with the file
    }
}

Solution 4

You can use Java.io.File.listFiles() method to get a list of all files and folders inside a folder.

Share:
17,494

Related videos on Youtube

Buras
Author by

Buras

Oracle DBA

Updated on September 16, 2022

Comments

  • Buras
    Buras over 1 year

    There is a folder: C:\\Users\..myfolder

    It contains .pdf files (or any other, say .csv). I cannot change the names of those files, and I do not know the number of those files. I need to loop all of the files one by one. How can I do this?

    (I know how to do this if I knew the names)

    • Andrew Thompson
      Andrew Thompson over 10 years
      Look at the methods of the File class, all you need is either in, or referenced from, there.
  • Buras
    Buras over 10 years
    Thank you very much. Especially for the additional filter thingy ...
  • rob
    rob over 10 years
    Consider using a FileFilter instead, then using File.listFiles(FileFilter). For example, your FileFilter can check that each element is, indeed, a file and check the extension.
  • Boris the Spider
    Boris the Spider over 10 years
    @rob Read the last part of the answer, there is no ready implementation of an extension filter in that api so there is little point in writing one yourself.
  • rob
    rob over 10 years
    @BoristheSpider To clarify: java.io.FileFilter or java.io.FilenameFilter. FileNameExtensionFilter is technically intended to be used with JFileChooser.
  • Boris the Spider
    Boris the Spider over 10 years
    @rob you will notice from the source code that there are no dependencies on other swing classes. It is fine to use outside of swing.
  • Buras
    Buras over 10 years
    Maybe should be if(extensionFilter.accept(child)) { instead of if(extensionFilter.accept(file)) {?
  • Boris the Spider
    Boris the Spider over 10 years
    @Buras fair point - typo. Fixed.
  • rob
    rob over 10 years
    @BoristheSpider Although there aren't dependencies on other Swing classes, I'm just pointing out that there are two other listFiles method signatures which are more correct for solving this problem. For instance, FileNameExtensionFilter will return true for any directory because that's the correct behavior for a file chooser. However, it is probably not the correct behavior in most other cases.