Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in java using asterisk and question marks to match the name of a file

Tags:

java

file-io

I want to write in java something like this:

public class MyMatcher 
{
   public static boolean isMatching(String filename, String param) { 
      ...
   }
}

filename would be the name of a file without the directory (e.g.: readme.txt, shares.csv, a nice song.mp3, ...)

param would be something like "*.mp3" to say all of the files ending with .mp3 and so on.

Note: param is not regular expression statement is more like the usual way of searching files like on textpad or eclipse or even the dos dir.

Can somebody suggest either how to do this or if there is some opensource library to do this ?

like image 868
chacko Avatar asked Apr 14 '11 11:04

chacko


People also ask

What does an asterisk do in Java?

An asterisk value is defined as '*' and for every character in the sentence, the character is compared to the pattern and a specific occurrence is replaced with the asterisk symbol. The final string is displayed on the console.

What is FileFilter in Java?

FileFilter is an abstract class used by JFileChooser for filtering the set of files shown to the user. See FileNameExtensionFilter for an implementation that filters using the file name extension. A FileFilter can be set on a JFileChooser to keep unwanted files from appearing in the directory listing.


2 Answers

String pattern = param.replaceAll ("\\*", ".*").replaceAll ("\\?", ".");
return filename.matches (pattern); 
like image 166
user unknown Avatar answered Nov 06 '22 16:11

user unknown


Apache Commons IO has a WilcardFileFilter:

The wildcard matcher uses the characters '?' and '*' to represent a single or multiple wildcard characters.

Example from the javadoc:

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*test*.java~*~");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
  System.out.println(files[i]);
}
like image 28
skaffman Avatar answered Nov 06 '22 16:11

skaffman