17

I'd like to find a file in a directory using wildcard. I have this in Java 6 but want to convert the code to Java 7 NIO:

 File dir = new File(mydir); 
 FileFilter fileFilter = new WildcardFileFilter(identifier+".*");
 File[] files = dir.listFiles(fileFilter);

There is no WildcardFileFilter, and I've played around a bit with globs.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Jabda
  • 1,752
  • 5
  • 26
  • 54
  • 1
    Have you read [Finding Files](https://docs.oracle.com/javase/tutorial/essential/io/find.html)? – Andy Turner May 06 '15 at 21:56
  • See http://stackoverflow.com/questions/20443793/allow-wildcards-to-search-for-subdirectories-from-a-parent-directory. It should help you in constructing right code for that. – wsl May 06 '15 at 21:56

3 Answers3

16

You can pass a glob to a DirectoryStream

import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
...

Path dir = FileSystems.getDefault().getPath( filePath );
DirectoryStream<Path> stream = Files.newDirectoryStream( dir, "*.{txt,doc,pdf,ppt}" );
for (Path path : stream) {
    System.out.println( path.getFileName() );
}
stream.close();
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
7

You could use a directory stream with a glob like:

DirectoryStream<Path> stream = Files.newDirectoryStream(dir, identifier+".*")

and then iterate the file paths:

for (Path entry: stream) {
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
olovb
  • 2,164
  • 1
  • 17
  • 20
0

This question was specifically for Java 7, but it also comes up as the first result for this question in general. With Java 8 and higher the way to do this wit NIO is to use Files.find with a BiPredicate<T, U>.

Stream<Path> stream = Files.find(
        Paths.get("/dirToSearch"),
        1, // Search depth of 1 in our case, set to >1 or -1 to explore subfolders
        (path, basicFileAttributes) -> {
            String filename = path.getFileName().toString();
            return filename.startsWith("identifier");
        }
);
// The stream is lazily populated
Path firstMatch = stream.findFirst().get();
Kyle Berezin
  • 597
  • 4
  • 20