如何打开Java中以特定前缀开头的所有文件?

如何打开Java中以特定前缀开头的所有文件?

问题描述:

有什么方法可以打开Java中以特定名称开头的目录中的某些文本文件吗?

Is there any way to open some of the text files in the directory that starts with a specific name in Java?

例如,在我的目录中,我有以下文件:

For example in my directory I have the following files:

Ab-01.txt
Ab-02.txt
Ab-03.txt
Ab-04.txt
SomethingElse.txt
NotRelated.txt

所以现在在我的Java代码中,我只想打开那些以" Ab-"

So now in my Java code I only want to open those files that starts with "Ab-"

是.使用 File.listFiles(FilenameFilter) :

例如:

File dir = new File("/path/to/directory");
File[] foundFiles = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("Ab-");
    }
});

for (File file : foundFiles) {
    // Process file
}    

当然,请将 accept()方法中的条件更改为所需的条件.因此,也许 name.startsWith("Ab-")&&name.endsWith(.txt").

Of course, change the condition in the accept() method to whatever you need. So maybe name.startsWith("Ab-") && name.endsWith(".txt").