项目中用到模糊查询获取文件,因为有些文件以指定头尾和时间节点来命名,在不知道是否有该文件或不知道文件全名的时候就用到了模糊查询来判断获取文件。
根据文件名称包含指定头尾字符判断是否存在对应文件
/**
*查找文件名称结尾为.txt的文件是否存在
*filepath 文件路径
*filename 文件名包含指定字符如:log_
**/
public String getFileName(String filepath, String filename){
File []fileArray = getFileList(filepath, filename);
if (fileArray == null) return null;
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i] != null)
&& fileArray[i].getName().endsWith(".txt")){
System.out.println("文件存在");
return fileArray[i].getName();
}
}
System.out.println("文件不存在");
return null;
}
/***获取filepath路径下包含str字符的文件, ***/
public static File [] getFileList(String filePath, String str){
File file = new File(filePath);
File [] fileArrays = new File[2];
int j = 0;
//获取该目录下所有文件和目录的绝对路径
File [] fileArray = file.listFiles(new FileFilterUtils(str));
if (fileArray != null){
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i] != null && fileArray[i].getName().contains(str)){
fileArrays[j] = fileArray[i];
j++;
if (j == 2) break;
}
}
}
return fileArrays;
}
文件过滤器,文件名filename开头返回true
public class FileFilterUtils implements FileFilter {
private String filename = "";
public FileFilterUtils(String fileName){
this.filename = fileName;
}
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()){
return true;
}else {
String name = pathname.getName();
if (name.startsWith(filename)){
return true;
}else {
return false;
}
}
}
}