Connor Gill
Connor Gill

Reputation: 63

How to use wildcards in filenames when reading in files

I'm working on an application that will read in SystemOut.Log files and process them. Sometimes archived files may be named slightly differently, such as SystemOut_10:20_09/07/2021-10:45_09/07/2021.Log. It's always of the form SystemOut(Some more text here).Log.

I had a little read up and stumbled across wildcards and came to the conclusion that if I were to pass SystemOut*.Log into my application as the filename it would work. But I was wrong.

I originally get my filename through a properties file like so.

fileName=prop.getProperty("fileName");

I then just tried to concatenate *.Log on the end.

fileName=fileName+"*.Log";

When I print out fileName it is "SystemOut*.Log" but when I pass in this filename to my method that reads files it doesn't work as no file is found with that name.

Am I making an error in the code or have I just misunderstood how wildcards work? Thanks

Upvotes: 0

Views: 1058

Answers (1)

Yiao SUN
Yiao SUN

Reputation: 978

Try FileUtils from Apache commons-io (listFiles and iterateFiles methods): The code you need is

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*.Log");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
   System.out.println(files[i]);
}

Upvotes: 1

Related Questions