文件夹下文件读取并在内存中模糊查询

文件夹下文件读取并模糊查询

最近遇到一个业务需求,觉得有点意思遂记录。
需求如此:查询指定文件夹下的所有文件,并获取文件信息,支持分页、模糊查询等。
分析:文件在文件夹下,不在数据库,因此读取文件夹所有文件,获取文件信息,在内存中实现分页、模糊查询等功能。
首先得引入一个包:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

这里用到它的作用是,把File类型文件转换为MultipartFile类型。
看代码:

  public R readFilesAndQuery(Map<String, Object> map) {
  		//这里写死指定文件夹路径,实际操作都是前端传入
        String filePaths = "C:\\Users\\Public\\Pictures\\Sample Pictures";
        Integer start = 1;
        Integer limit = 10;
        String fileName = null;
        String startTime = null;
        String endTime = null;
        Date startTimeReg = null;
        Date endTiemReg = null;
        Integer total = null;
        Integer totalPage = null;
        FileInputStream fis = null;
        Map<String, Object> data = new HashMap<>();
        data.clear();
        if (null != map && map.get("limit") != null) {
            limit = Integer.parseInt((String) map.get("limit"));
        }
        if (null != map && map.get("start") != null) {
            start = Integer.parseInt((String) map.get("start"));
        }
        if (null != map && map.get("fileName") != null) {
            fileName = (String) map.get("fileName");
        }
        try {
            if (null != map && map.get("startTime") != null) {
                startTime = (String) map.get("startTime");
                if (!StringUtils.isBlank(startTime)) {
                    startTimeReg = sdf.parse(startTime);
                }
            }
            if (null != map && map.get("endTime") != null) {
                endTime = (String) map.get("endTime");
                if (!StringUtils.isBlank(endTime)) {
                    endTiemReg = sdf.parse(endTime);
                }
            }
            List<FileInfoVo> list = new ArrayList<>();
            File file = new File(filePaths);
            if (null != file && file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                //获取File文件的大小,这里先转换成MultipartFile
                    MultipartFile multipartFile = new MockMultipartFile(f.getName(),new FileInputStream(f));
                    //这里是byte单位,跟M还有1024*1024de 差距
                    long size = multipartFile.getSize();
                    FileInfoVo fif = new FileInfoVo();
                    fif.setFileSize(size+"");
                    Long lastTime = f.lastModified();
                    Date lastModified = new Date(lastTime);
                    fif.setUploadDate(sdf.format(lastModified));
                    String name = f.getName();
                    fif.setFileName(name);
                    fif.setPath(f.getPath());

                    list.add(fif);
                }
            }
            String finalFileName = fileName;
            Date finalstartTimeReg = startTimeReg;
            Date finalendTimeReg = endTiemReg;
            List<FileInfoVo> collect = list.stream().filter(item -> {
                //获取文件名
                String fileRealName = null;
                if (item.getFileName().lastIndexOf(".") != -1) {
                    fileRealName = item.getFileName().substring(0, item.getFileName().lastIndexOf("."));
                } else {
                    fileRealName = item.getFileName();
                }
                if (null == finalFileName) {
                    return true;
                }
                /**
                *内存中的数据进行模糊查询的方法
                **/
                String regex = ".*" + finalFileName + ".*";
                if (fileRealName.matches(regex)) {
                    return true;
                }
                return false;
            }).filter(ite -> {
                String uploadTime = ite.getUploadDate();
                Date uploadTimeReg = null;
                if (!StringUtils.isBlank(uploadTime)) {
                    try {
                        uploadTimeReg = sdf.parse(uploadTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //时间的比较:Date类型,a.after(b)  a在b之后
                    if (null != finalstartTimeReg && finalstartTimeReg.after(uploadTimeReg)) {
                        return false;
                    } else {
                        return true;
                    }
                }
                return true;
            }).filter(it -> {
                String uploadTime = it.getUploadDate();
                Date uploadTimeReg = null;
                if (!StringUtils.isBlank(uploadTime)) {
                    try {
                        uploadTimeReg = sdf.parse(uploadTime);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //时间的比较:Date类型,a.before(b)  a在b之前
                    if (null != finalendTimeReg && finalendTimeReg.before(uploadTimeReg)) {
                        return false;
                    } else {
                        return true;
                    }
                }
                return true;
            }).collect(Collectors.toList());

            if (null != collect && collect.size() > 0) {
                total = collect.size();
            } else {
                total = 0;
            }
            if (limit > 0) {
            //计算总页数
                totalPage = (int) Math.ceil((double) total / limit);
            } else {
                totalPage = 0;
            }
            Integer fromIndex = (start - 1) * limit;
            Integer toIndex = start * limit;
            //防止最后一页不满
            if (toIndex > total) {
                toIndex = total;
            }
            /**
             *截取集合
             * @param fromIndex low endpoint (inclusive) of the subList
             * @param toIndex high endpoint (exclusive) of the subList
             * 包含起始条,不包含最后一条
             */
            List<FileInfoVo> subList = list.subList(fromIndex, toIndex);

            data.put("total", total);
            data.put("pageSize", limit);
            data.put("totalPage", totalPage);
            data.put("currPage", start);
            data.put("data", subList);


        } catch (Exception e) {
            e.printStackTrace();
        }


        return R.ok("查询成功!").put("data", data);
    }

本文技术含量不是很高,但包含一些常用技术点:

①读取文件夹下的所有文件:file.listFiles();File类型文件转换为MultipartFile 类型(要导入新包)
MultipartFile multipartFile = new MockMultipartFile(f.getName(),new FileInputStream(f))
这里仅仅是为了获取文件大小
③ 内存中的内容的模糊匹配
 String regex = ".*" + finalFileName + ".*";
                if (fileRealName.matches(regex)) {
                    return true;
                }
 ④ Date类型的日期比较大小:a.before(b)  a在b之前,a.after(b)  a在b之后
 ⑤集合的截取:包含起始条,不包含最后一条(因为集合是从第0开始的)
 subList:
			 @param fromIndex low endpoint (inclusive) of the subList
              @param toIndex high endpoint (exclusive) of the subList
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神雕大侠mu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值