Java 文件名过滤器的使用

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

Use of FilenameFilter

javafile-iojava-io

提问by Leem.fin

I have a directory:

我有一个目录:

File dir = new File(MY_PATH);

I would like to list all the files whose name is indicated as integer numbers strings, e.g. "10", "20".
I know I should use:

我想列出名称以整数字符串表示的所有文件,例如“10”、“20”。
我知道我应该使用:

dir.list(FilenameFilter filter);

How to define my FilenameFilter?

如何定义我的FilenameFilter

P.S.I mean the file name could be any integer string, e.g. "10" or "2000000" or "3452345". No restriction in the number of digits as long as the file name is a integer string.

PS我的意思是文件名可以是任何整数字符串,例如“10”或“2000000”或“3452345”。只要文件名是整数字符串,就没有位数限制。

采纳答案by Maroun

You should overrideacceptin the interfaceFilenameFilterand make sure that the parameter namehas only numeric chars. You can check this by using matches:

您应该在界面中覆盖并确保参数只有数字字符。您可以使用以下方法检查:acceptFilenameFilternamematches

String[] list = dir.list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.matches("[0-9]+");
    }
});

回答by A4L

preferably as an instance of an anonymous inner class passsed as parameter to File#list.

最好作为匿名内部类的实例作为参数传递给File#list

for example, to list only files ending with the extension .txt:

例如,仅列出以扩展名结尾的文件.txt

File dir = new File("/home");
String[] list = dir.list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

To list only files whose filenames are integers of exactly 2 digits you can use the following in the accept method:

要仅列出文件名恰好为 2 位整数的文件,您可以在 accept 方法中使用以下内容:

return name.matches("\d{2}");

for one or more digits:

对于一位或多位数字:

return name.matches("\d+");    

EDIT(as response to @crashprophet's comment)

编辑(作为对@crashprophet 评论的回应)

Pass a set of extensions of files to list

将一组文件扩展名传递给列表

class ExtensionAwareFilenameFilter implements FilenameFilter {

    private final Set<String> extensions;

    public ExtensionAwareFilenameFilter(String... extensions) {
        this.extensions = extensions == null ? 
            Collections.emptySet() : 
                Arrays.stream(extensions)
                    .map(e -> e.toLowerCase()).collect(Collectors.toSet());
    }

    @Override
    public boolean accept(File dir, String name) {
        return extensions.isEmpty() || 
            extensions.contains(getFileExtension(name));
    }

    private String getFileExtension(String filename) {
        String ext = null;
        int i = filename .lastIndexOf('.');
        if(i != -1 && i < filename .length()) {
            ext = filename.substring(i+1).toLowerCase();
        }
        return ext;
    }
}


@Test
public void filefilter() {
    Arrays.stream(new File("D:\downloads").
        list(new ExtensionAwareFilenameFilter("pdf", "txt")))
            .forEach(e -> System.out.println(e));
}

回答by user2607028

I do it as:

我这样做:

    File folder = new File(".");
    File[] listOfFiles = folder.listFiles();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            if (file.toString().endsWith(".sql")) {
                System.out.println(file.getName());
            }
        }
    }
    System.out.println("End!!");

回答by Grzegorz Piwowarek

Since Java 8, you can simply use a lambda expression to specify your custom filter:

从 Java 8 开始,您可以简单地使用 lambda 表达式来指定您的自定义过滤器:

dir.list((dir1, name) -> name.equals("foo"));

In the above example, only files with the name "foo" will make it through. Use your own logic of course.

在上面的示例中,只有名为“foo”的文件才能通过。当然使用你自己的逻辑。

回答by Dave

Here's the what I wound up with. It uses a nice lambda expression that can be easily twisted to your own designs...

这是我的结局。它使用了一个很好的 lambda 表达式,可以很容易地扭曲到您自己的设计中......

File folder = new File(FullPath);
String[] files = folder.list((lamFolder, lamName) -> lamName.matches("[0-9]+"));
if(files == null) {
    System.out.println("Stuff wrongly: no matching files found.");
} else {
    for(String file : files) {
        System.out.println("HOORAY: I found this "+ file);
    }
}