<分区>
我需要实现
File[] files = getFiles( String folderName, String ptrn );
其中 ptrn 是命令提示符样式模式,如“*2010*.txt”
我熟悉 FilenameFilter 类,但无法实现
public boolean accept(文件目录,字符串文件名)
因为 String.matches() 不接受这样的模式。
谢谢!
<分区>
我需要实现
File[] files = getFiles( String folderName, String ptrn );
其中 ptrn 是命令提示符样式模式,如“*2010*.txt”
我熟悉 FilenameFilter 类,但无法实现
public boolean accept(文件目录,字符串文件名)
因为 String.matches() 不接受这样的模式。
谢谢!
最佳答案
String#matches()
接受 regular expression patterns .
“外行”变体 *2010*.txt
的正则表达式变体将是 .*2010.*\.txt
。
所以以下应该有效:
public boolean accept(File dir, String name) {
return name.matches(".*2010.*\\.txt");
}
双反斜杠只是代表一个实际的反斜杠,因为反斜杠本身是 Java 的 String
中的转义字符。
或者,您也可以使用其他 String
方法在没有正则表达式的情况下执行此操作:
public boolean accept(File dir, String name) {
return name.contains("2010") && name.endsWith(".txt");
}
您最好的选择可能是让 ptrn
代表一个真正的 正则表达式模式,或者将每个 .
字符串替换为 \。
和 *
与 .*
使其成为有效的正则表达式模式。
public boolean accept(File dir, String name) {
return name.matches(ptrn.replace(".", "\\.").replace("*", ".*"));
}
关于java 文件名过滤模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3057621/