FTPクライアントを使用して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(“/”)」は省略可能なことに注意してください。その場合、現在の作業ディレクトリ内で直接新たなディレクトリを作成できます。