javaj代码实现ftp删除文件夹
时间: 2023-11-20 08:08:18 浏览: 75
以下是Java代码实现FTP删除文件夹的示例:
```java
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
public class FtpDeleteFolderExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
String folderPath = "/example/folder/to/delete";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(folderPath);
deleteFolder(ftpClient, folderPath);
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Folder deleted successfully.");
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
private static void deleteFolder(FTPClient ftpClient, String folderPath) throws IOException {
ftpClient.changeWorkingDirectory(folderPath);
for (String fileName : ftpClient.listNames()) {
if (fileName.equals(".") || fileName.equals("..")) {
continue;
}
String filePath = folderPath + "/" + fileName;
if (ftpClient.listFiles(filePath).length > 0) {
deleteFolder(ftpClient, filePath);
}
ftpClient.deleteFile(filePath);
}
ftpClient.changeToParentDirectory();
ftpClient.removeDirectory(folderPath);
}
}
```
在这个示例中,我们使用 Apache Commons Net 库中的 FTPClient 类来连接 FTP 服务器并执行删除操作。该示例列出了要删除的文件夹中的所有文件和子文件夹,并递归地删除它们。最后,它删除要删除的文件夹本身。
阅读全文