Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open all files that starts with specific prefix in java?

Tags:

java

file

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

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

like image 769
DalNM Avatar asked Jul 12 '11 15:07

DalNM


1 Answers

Yes. Use File.listFiles(FilenameFilter):

As an example:

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
}    

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

like image 143
Adam Batkin Avatar answered Sep 23 '22 21:09

Adam Batkin