本文将开发一个示例,说明如何使用 Apache Commons Net 库删除远程 FTP 服务器上的非空目录(包括子目录和文件)。
要删除非空目录的所有内容,重要的是列出目录的所有内容,其子目录,子目录的子目录等(递归列出)。
为了可重用,下面开发一个工具类:
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
/**
* This utility class implements a method that removes a non-empty directory
* on a FTP server.
*/
public class FTPUtil {
/**
* Removes a non-empty directory by delete all its sub files and
* sub directories recursively. And finally remove the directory.
*/
public static void removeDirectory(FTPClient ftpClient, String parentDir,
String currentDir) throws IOException {
String dirToList = parentDir;
if (!currentDir.equals("")) {
dirToList += "/" + currentDir;
}
FTPFile[] subFiles = ftpClient.listFiles(dirToList);
if (subFiles != null && subFiles.length > 0) {
for (FTPFile aFile : subFiles) {
String currentFileName = aFile.getName();
if (currentFileName.equals(".") || currentFileName.equals("..")) {
// skip parent directory and the directory itself
continue;
}
String filePath = parentDir + "/" + currentDir + "/"
+ currentFileName;
if (currentDir.equals("")) {
filePath = parentDir + "/" + currentFileName;
}
if (aFile.isDirectory()) {
// remove the sub directory
removeDirectory(ftpClient, dirToList, currentFileName);
} else {
// delete the file
boolean deleted = ftpClient.deleteFile(filePath);
if (deleted) {
System.out.println("DELETED the file: " + filePath);
} else {
System.out.println("CANNOT delete the file: "
+ filePath);
}
}
}
// finally, remove the directory itself
boolean removed = ftpClient.removeDirectory(dirToList);
if (removed) {
System.out.println("REMOVED the directory: " + dirToList);
} else {
System.out.println("CANNOT remove the directory: " + dirToList);
}
}
}
}
注意,方法 removeDirectory() 使用的是递归算法,如果要列出的是目录,则该方法将调用自身。
下面的测试程序先连接到 FTP 服务器,删除目录“/Test”,最后断开与服务器的连接:
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
/**
* This program demonstrates how to remove a non-empty directory on a FTP
* server, using Apache Commons Net FTP library.
*
*/
public class FTPRemoveNonEmptyDir {
public static void main(String[] args) {
String server = "www.91tech.org";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
// connect and login to the server
ftpClient.connect(server, port);
ftpClient.login(user, pass);
// use local passive mode to pass firewall
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
String dirPath = "/Test";
FTPUtil.removeDirectory(ftpClient, dirPath, "");
// log out and disconnect from the server
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
假设要删除的 FTP 服务器上的目录“/Test”结构如下:
运行代码后得到以下输出: