在Java中使用Apache Commons Net库中的FTPClient创建多级文件夹,可以按照以下步骤进行:
-
导入FTPClient类:
import org.apache.commons.net.ftp.FTPClient;
-
创建FTPClient对象:
FTPClient ftpClient = new FTPClient();
-
连接到FTP服务器:
ftpClient.connect(server, port); // 传入FTP服务器地址和端口号 ftpClient.login(username, password); // 传入FTP服务器的用户名和密码
-
设置文件传输模式为被动模式(可选):
ftpClient.enterLocalPassiveMode();
-
检查连接状态:
if (ftpClient.getReplyCode() != 230) { throw new IOException("Failed to connect to FTP server"); }
-
开启被动模式传输(可选):
ftpClient.enterLocalPassiveMode();
-
设置FTP服务器工作目录为根目录:
ftpClient.changeWorkingDirectory("/");
-
创建多级文件夹:
String[] folders = { "folder1", "folder2", "folder3" }; // 指定要创建的文件夹路径 for (String folder : folders) { ftpClient.makeDirectory(folder); ftpClient.changeWorkingDirectory(folder); }
-
断开与FTP服务器的连接:
ftpClient.logout(); // 退出登录 ftpClient.disconnect(); // 断开连接
完整的示例代码如下:
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
public class FTPCreateMultiLevelDirectories {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String username = "username";
String password = "password";
String[] folders = { "folder1", "folder2", "folder3" };
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
if (ftpClient.getReplyCode() != 230) {
throw new IOException("Failed to connect to FTP server");
}
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory("/");
for (String folder : folders) {
ftpClient.makeDirectory(folder);
ftpClient.changeWorkingDirectory(folder);
}
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就可以创建多级文件夹。请注意,如果要在已有的文件夹路径上创建新的文件夹,可以省略第7步中的`ftpClient.changeWorkingDirectory("/")`,直接在当前工作目录下创建新的文件夹即可。