开发者

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

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 ?


String pattern = param.replaceAll ("\\*", ".*").replaceAll ("\\?", ".");
return filename.matches (pattern); 


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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜