Java 实现从Ftp批量删除某一文件夹内的文件
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
public class DeleteFtpFileDemo {
public static void main(String[] args) {
deleteFtpFile();
}
public static void deleteFtpFile(){
final String FTP_IP = "your ftpIP";
final String FTP_PORT = "your port";
final String FTP_USER = "your username";
final String FTP_PASSWORD = "your password";
final String FTP_PATH = "your ftpPath";
FTPClient ftpClient = new FTPClient();
boolean login = false;
try {
System.out.println("正在连接到----"+FTP_IP+":"+FTP_PORT);
ftpClient.connect(FTP_IP, Integer.parseInt(FTP_PORT));
System.out.println("已连接上----"+FTP_IP+":"+FTP_PORT);
login = ftpClient.login(FTP_USER, FTP_PASSWORD);
if (login) {
System.out.println(FTP_USER+"已成功登录");
} else {
System.err.println("登录ftp失败 !");
return;
}
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
System.err.println("ftp 连接密码不正确! 已断开连接");
return;
}else{
ftpClient.setSoTimeout(50000);
}
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("FTP 登录出错!");
}
Boolean changeDirectory = null;
try {
changeDirectory = ftpClient.changeWorkingDirectory(FTP_PATH);
if (changeDirectory){
System.out.println("已切换到:"+FTP_PATH+"路径下!");
}
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("FTP 切换工作路径时,ftp路径出错: [ " + FTP_PATH + " ]");
}
if (!changeDirectory) throw new IllegalArgumentException("FTP 切换工作路径失败: [ " + FTP_PATH + " ]");
try {
FTPFile[] fs = ftpClient.listFiles();
System.out.println(FTP_PATH +"路径下文件数量:"+fs.length);
if (fs.length == 0){
System.out.println(FTP_PATH +"路径下无可删除文件");
}else {
FTPFile ff = null;
System.out.println("开始执行循环,准备删除文件!");
for (int i = 0; i < fs.length; i++) {
ff = fs[i];
String fileName = ff.getName();
System.out.println("文件名: " + fileName + "_____" + i);
boolean delete = ftpClient.deleteFile(fileName);
if (delete) {
System.out.println("文件 [ " +FTP_PATH + "/" + fileName + " ] 删除成功!");
} else {
System.out.println("文件 [ " + fileName + " ] 删除失败!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("发生错误");
} finally {
if (login) {
try {
ftpClient.logout();
System.out.println("已退出登录");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ftpClient.disconnect();
System.out.println("已断开连接!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}