在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("/")
,直接在當前工作目錄下創建新的文件夾即可。