Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7 nio list directory with wildcard

Tags:

java

nio

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.

like image 331
Jabda Avatar asked May 06 '15 21:05

Jabda


2 Answers

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();
like image 132
RealHowTo Avatar answered Oct 10 '22 19:10

RealHowTo


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) {
}
like image 23
olovb Avatar answered Oct 10 '22 18:10

olovb