列出与 Java 中的模式匹配的目录中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2102952/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:34:17  来源:igfitidea点击:

Listing files in a directory matching a pattern in Java

javaio

提问by Omar Kooheji

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

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

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

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

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

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

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

采纳答案by Kevin

See File#listFiles(FilenameFilter).

请参阅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);
}

回答by jjnguy

The following code will create a list of files based on the accept method of the FileNameFilter.

以下代码将基于 .accept 方法创建文件列表FileNameFilter

List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".exe"); // or something else
        }}));

回答by OscarRyz

What about a wrapper around your existing code:

现有代码的包装器怎么样:

public Collection<File> getMatchingFiles( String directory, String extension ) {
     return new ArrayList<File>()( 
         getAllFilesThatMatchFilenameExtension( directory, extension ) );
 }

I will throw a warning though. If you can live with that warning, then you're done.

不过我会发出警告。如果你能忍受那个警告,那么你就完成了。

回答by Tarek

Since java 7 you can the java.niopackage to achieve the same result:

从 java 7 开始,您可以使用java.nio包来实现相同的结果:

Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
    for (Path entry: stream) {
        files.add(entry.toFile());
    }
    return files;
} catch (IOException x) {
    throw new RuntimeException(String.format("error reading folder %s: %s",
    dir,
    x.getMessage()),
    x);
}

回答by mr T

Since Java 8 you can use lambdas and achieve shorter code:

从 Java 8 开始,您可以使用 lambdas 并实现更短的代码:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));

回答by Manash Ranjan Dakua

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class CharCountFromAllFilesInFolder {

    public static void main(String[] args)throws IOException {

        try{

            //C:\Users\MD\Desktop\Test1

            System.out.println("Enter Your FilePath:");

            Scanner sc = new Scanner(System.in);

            Map<Character,Integer> hm = new TreeMap<Character, Integer>();

            String s1 = sc.nextLine();

            File file = new File(s1);

            File[] filearr = file.listFiles();

            for (File file2 : filearr) {
                System.out.println(file2.getName());
                FileReader fr = new FileReader(file2);
                BufferedReader br = new BufferedReader(fr);
                String s2 = br.readLine();
                for (int i = 0; i < s2.length(); i++) {
                    if(!hm.containsKey(s2.charAt(i))){
                        hm.put(s2.charAt(i), 1);
                    }//if
                    else{
                        hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
                    }//else

                }//for2

                System.out.println("The Char Count: "+hm);
            }//for1

        }//try
        catch(Exception e){
            System.out.println("Please Give Correct File Path:");
        }//catch
    }
}