在Java中使用Apache Commons Net库中的FTPClient创建多级文件夹,可以按照以下步骤进行:
import org.apache.commons.net.ftp.FTPClient;
FTPClient ftpClient = new FTPClient();
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();
ftpClient.changeWorkingDirectory("/");
String[] folders = { "folder1", "folder2", "folder3" }; // 指定要创建的文件夹路径
for (String folder : folders) {
ftpClient.makeDirectory(folder);
ftpClient.changeWorkingDirectory(folder);
}
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("/")
,直接在当前工作目录下创建新的文件夹即可。