/** * 获取ftp文件列表 * ".*\\.txt" :匹配所有以".txt" 结尾的文件名。其中,星号(*)表示任意字符序列,反斜杠(\)用于转义点号(.)字符。 * ".*" + "任意字符" + ".*\\.txt" :匹配所有包含 "表示匹配任意多个任意字符"和以".txt" 结尾的文件名。其中,星号(*)表示任意字符序列,反斜杠(\)用于转义点号(.)字符。 * @param params * @return */ @PostMapping("/getFTPFileList") @ResponseBody public Result getFTPFileList(@RequestBody Map<String,Object> params) { FTPClient ftpClient = new FTPClient(); List<Map<String, Object>> list = new ArrayList<>(); FTPFile[] page = new FTPFile[0]; int pageNum = ("".equals(String.valueOf(params.get("pageNo"))) || params.get("pageNo") == null) ? 1 : Integer.valueOf(String.valueOf(params.get("pageNo"))); int pageSize = ("".equals(String.valueOf(params.get("pageSize"))) || params.get("pageSize") == null) ? 20 : Integer.valueOf(String.valueOf(params.get("pageSize"))); int start = (pageNum - 1) * pageSize; int end = start + pageSize - 1; try { System.out.println("开始连接ftp"); ftpClient.connect(host, port); ftpClient.login(username, password); // ftpClient.connect(ip, pr); // ftpClient.login(user, pass); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return Result.error("ftp连接失败:" + reply); }else{ System.out.println("ftp连接成功:" + reply); } ftpClient.enterLocalPassiveMode(); //被动模式 String p = ("".equals(String.valueOf(params.get("path"))) || params.get("path") == null) ? path : String.valueOf(params.get("path")); String f = ("".equals(String.valueOf(params.get("file"))) || params.get("file") == null) ? file : ".*" + String.valueOf(params.get("file")).replaceAll("_","") + ".*"; System.out.println("正则匹配:" + f); FTPFile[] files = ftpClient.listFiles(p); //根据名称进行正则匹配文件 Pattern filePattern = Pattern.compile(f); if (files == null || files.length < start) { return Result.success(new FTPFile[0]); } int count = Math.min(end + 1, files.length) - start; page = new FTPFile[count]; //对结果进行分页 System.arraycopy(files, start, page, 0, count); for (FTPFile file : page) { if (file.isFile() && filePattern.matcher(file.getName()).matches()) { Map<String, Object> map = new HashMap<>(); map.put("name", file.getName()); //计算大小MB double megabytes = (double) file.getSize() / 1048576; if (megabytes >= 1024) { //计算大小G megabytes = megabytes / 1024; String formattedNumber = String.format("%.1f", megabytes); map.put("size", formattedNumber + "G"); } else { String formattedNumber = String.format("%.1f", megabytes); map.put("size", formattedNumber + "MB"); } list.add(map); } } } catch (IOException e) { throw new RuntimeException(e); } finally { try { ftpClient.logout(); ftpClient.disconnect(); System.out.println("已关闭ftp链接"); } catch (IOException e) { throw new RuntimeException(e); } } return Result.success(list);
测试结果:
入参:path 是文件存储路径, file 是文件名称,支持模糊查询
{ "path":"/visit", "file":"202305", "pageNum": 1, "pageSize": 20 }
标签:ftp,java,String,get,valueOf,列表,params,file,ftpClient From: https://www.cnblogs.com/ljmm/p/17476829.html