4

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)

Buras
  • 3,069
  • 28
  • 79
  • 126

4 Answers4

5

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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • Thank you very much. Especially for the additional filter thingy ... – Buras Oct 04 '13 at 21:00
  • 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. – rob Oct 04 '13 at 21:05
  • @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. – Boris the Spider Oct 04 '13 at 21:06
  • @BoristheSpider To clarify: `java.io.FileFilter` or `java.io.FilenameFilter`. `FileNameExtensionFilter` is technically intended to be used with `JFileChooser`. – rob Oct 04 '13 at 21:11
  • @rob you will notice from [the source code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/filechooser/FileNameExtensionFilter.java) that there are no dependencies on other swing classes. It is fine to use outside of swing. – Boris the Spider Oct 04 '13 at 21:13
  • Maybe should be `if(extensionFilter.accept(child)) {` instead of `if(extensionFilter.accept(file)) {`? – Buras Oct 04 '13 at 21:22
  • @Buras fair point - typo. Fixed. – Boris the Spider Oct 04 '13 at 21:23
  • @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. – rob Oct 04 '13 at 21:24
  • How can i create a String using path_to_dir + file name? i have tried to use StringBuffer("path").append("child") but it is not working. – Andrew Ramnikov Oct 25 '16 at 08:11
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
    }
}
user2827100
  • 186
  • 4
  • Use File.listFiles(FilenameFilter) or File.listFiles(FileFilter) to only process results which have certain properties, such as filename extension. – rob Oct 04 '13 at 20:59
  • String[] bits = file.getName().split("\\."); – Python Lord Jun 08 '17 at 18:07
3

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
2

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

Ali Hashemi
  • 3,158
  • 3
  • 34
  • 48