带有通配符的 Java 7 nio 列表目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30088245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 7 nio list directory with wildcard
提问by Jabda
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:
我想使用通配符在目录中查找文件。我在 Java 6 中有这个,但想将代码转换为 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.
没有WildcardFileFilter
,我玩过一些球体。
采纳答案by RealHowTo
You can pass a glob to a DirectoryStream
您可以将 glob 传递给 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();
回答by olovb
You could use a directory streamwith a globlike:
DirectoryStream<Path> stream = Files.newDirectoryStream(dir, identifier+".*")
and then iterate the file paths:
然后迭代文件路径:
for (Path entry: stream) {
}