模糊查询文件是否存在

项目中用到模糊查询获取文件,因为有些文件以指定头尾和时间节点来命名,在不知道是否有该文件或不知道文件全名的时候就用到了模糊查询来判断获取文件。

根据文件名称包含指定头尾字符判断是否存在对应文件

/**
*查找文件名称结尾为.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;
            }
        }
    }

}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值