日常跑數(shù)的文件存放于FTP服務器需要定期刪除争便;寫一個刪除FTP指定路徑指定日期之前文件的工具類断医,后續(xù)或可應用于定時任務調度。
使用到的jar包:commons-net-3.8.0.jar
入參:FTP指定文件夾路徑斩启;指定日期時間
代碼:
package com.example.demo.controller;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
public class FTPFileClean {
private Logger logger= LoggerFactory.getLogger(getClass());
private FTPClient ftp;
private Date date;
@RequestMapping("/FTPFileClean")
public String clean(String vFolder, String vDate) {
// 獲取FTP參數(shù)
String ftpIP = "192.168.0.21";
String ftpUserName = "username";
String ftpPassword = "password";
int ftpPort = 21;
this.ftp = new FTPClient();
this.ftp.setControlEncoding("UTF-8");
try {
int reply;
this.ftp.connect(ftpIP, ftpPort);
this.ftp.login(ftpUserName, ftpPassword);
reply = this.ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftp.disconnect();
return "FTP登錄失敗";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
date = sdf.parse(vDate);
//遞歸刪除該文件下過期文件
deleteFile(vFolder);
ftp.logout();
return "成功";
}
catch (Exception e) {
return "刪除文件失斖么亍荣挨!" + e.getMessage();
}
finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
/**
* 遞歸刪除文件
* @param vFolder
* @throws IOException
*/
private void deleteFile(String vFolder) throws IOException {
if (vFolder.startsWith("/") && vFolder.endsWith("/")) {
FTPFile[] files = null;
this.ftp.changeWorkingDirectory(vFolder);
//需要設置一下模式才能獲取子文件列表
this.ftp.enterLocalPassiveMode();
files = this.ftp.listFiles();
for (FTPFile file : files) {
if (file.isFile()) {
// 判斷是否在指定日期之前
if (new Date(file.getTimestamp().getTimeInMillis()).before(date)) {
//需要再設置一下ftp路徑才能刪除
this.ftp.changeWorkingDirectory(vFolder);
this.ftp.deleteFile(file.getName());
System.out.println("刪除文件:"+file.getName());
}
}
else if (file.isDirectory()) {
// 需要判斷是否為該目錄(./)及上級目錄(../)朴摊。否則納入遞歸會陷死循環(huán)
if (!".".equals(file.getName()) && !"..".equals(file.getName())) {
deleteFile(vFolder + file.getName() + "/");
}
}
}
}
}
}