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-
“
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")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With