Search for Files in Directory Using Wildcards in Java
(Please see my previous post about how to do this for very simple cases in Java.)
Sometimes you want to be able to search for files using patterns. For example, you might want to find all the files in a directory with a .htm extension. A reasonable way to accomplish this is to use regular expressions. Below is a solution I put together. I don’t claim it to be perfect. But I think it will work for most scenarios. If you want a more intricate solution (but also more overhead), see this post.
import java.io.*; import java.util.regex.*; public class WildCardFileFilter implements FileFilter { private String _pattern; public WildCardFileFilter(String pattern) { _pattern = pattern.replace("*", ".*").replace("?", "."); } public boolean accept(File file) { return Pattern.compile(_pattern).matcher(file.getName()).find(); } }
You would invoke this in a way such as the code below.
File dir = new File("C:\\Temp\\"); File[] files = dir.listFiles(new WildCardFileFilter("*s?an?ard*.htm")); for (File file : files) System.out.println(file.getName());
A ? is a wildcard for any single character, while a * represents zero or more wildcard characters next to each other. This code would find files with names such as the following:
- the_standard.htm
- the_spaniard.htm
- standard.htm
- spaniards.htm
- spaniardssssss.htm
Please leave me a comment if this was helpful or if you have suggestions to improve it.
Very helpful, thanks a lot
Thanks! I needed to add in the constructor
_pattern = “^” + _pattern + “$”;
to match the full string (instead of partial). Otherwise *.htm was matching 1.htm.txt as well…
Neatly done!
You may wish to replace “.” with “\.” too, for completeness.
Hi,
I find this code much useful for my project, thanks a lot for the same.
Hi,,
I am unable to track down ur program. Could u please mail me the complete code for searching a file in the drive. It will be very helpfull to me if u do so….
I”m not sure I understand what you’re looking for. Please explain more.
Hello,
i tried to search a file and landed upon no ERROR & no output it would be great if u can mail the entire code for reference as this snipet dosent seems of much help please…
more over can u also help for finding a file on the network…
Thanks in Advance..
Rohit sharma,
I’m sorry but I don’t really understand the problem you’re having. The code should be fully functional. If it’s not working, please provide an example of the code you are using, and I’ll see if I can help.
Your example is nice.
But I have one doubt, if you have to find the file deep in directory structure containing directories inside directory, how we will search the file into it without recursion and also not having extra load of searching.
Java takes care of recursion for you. What do you mean by extra load of search?