在Java中使用Apache Commons Net庫(kù)中的FTPClient創(chuàng)建多級(jí)文件夾,可以按照以下步驟進(jìn)行:
import org.apache.commons.net.ftp.FTPClient;
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port); // 傳入FTP服務(wù)器地址和端口號(hào)
ftpClient.login(username, password); // 傳入FTP服務(wù)器的用戶(hù)名和密碼
ftpClient.enterLocalPassiveMode();
if (ftpClient.getReplyCode() != 230) {
throw new IOException("Failed to connect to FTP server");
}
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory("/");
String[] folders = { "folder1", "folder2", "folder3" }; // 指定要?jiǎng)?chuàng)建的文件夾路徑
for (String folder : folders) {
ftpClient.makeDirectory(folder);
ftpClient.changeWorkingDirectory(folder);
}
ftpClient.logout(); // 退出登錄
ftpClient.disconnect(); // 斷開(kāi)連接
完整的示例代碼如下:
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();
}
}
}
這樣就可以創(chuàng)建多級(jí)文件夾。請(qǐng)注意,如果要在已有的文件夾路徑上創(chuàng)建新的文件夾,可以省略第7步中的ftpClient.changeWorkingDirectory("/")
,直接在當(dāng)前工作目錄下創(chuàng)建新的文件夾即可。