列出与 Java 中的模式匹配的目录中的文件 [英] Listing files in a directory matching a pattern in Java

查看:19
本文介绍了列出与 Java 中的模式匹配的目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来获取与给定目录中的模式(pref regex)匹配的文件列表.

I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.

我在网上找到了一个使用apache的commons-io包的教程,代码如下:

I've found a tutorial online that uses apache's commons-io package with the following code:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
  File directory = new File(directoryName);
  return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}

但这只是返回一个基本集合(根据 文档 它是 java.io.File).有没有办法做到这一点,返回一个类型安全的泛型集合?

But that just returns a base collection (According to the docs it's a collection of java.io.File). Is there a way to do this that returns a type safe generic collection?

推荐答案

参见 File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}

这篇关于列出与 Java 中的模式匹配的目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆