Java 7 nio list directory with wildcard

匆匆过客 提交于 2020-01-31 22:53:33

问题


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.


回答1:


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();



回答2:


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) {
}


来源:https://stackoverflow.com/questions/30088245/java-7-nio-list-directory-with-wildcard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!