如何打开Java中以特定前缀开头的所有文件? [英] How to open all files that starts with specific prefix in java?

查看:82
本文介绍了如何打开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").

这篇关于如何打开Java中以特定前缀开头的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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