FTP サーバーにサブディレクトリを作成するために FTPClient を使用しています。「ルート」の下にディレクトリ「アーカイブ」を作成したい。サブディレクトリの作成には、次の関数を使用します。
boolean s = ftNew.makeDirectory("/"+folderName+"/Archive");
しかし、それはfalseを返し、サブディレクトリ「アーカイブ」を作成できません。これを解決するには?
FTP サーバーにサブディレクトリを作成するために FTPClient を使用しています。「ルート」の下にディレクトリ「アーカイブ」を作成したい。サブディレクトリの作成には、次の関数を使用します。
boolean s = ftNew.makeDirectory("/"+folderName+"/Archive");
しかし、それはfalseを返し、サブディレクトリ「アーカイブ」を作成できません。これを解決するには?
FTPClient の makeDirectory は true または false を返しますが、あまり有用ではなく、あいまいな結果です。幸いなことに、正確な FTP ステータス メッセージを報告するようにコードを改善できます。
必要なものは次のとおりです。
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
すべての FTPClient メソッドの後にこれを呼び出します。次に例を示します。
package apachenet.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class App {
public static void main( String[] args ) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("127.0.0.1");
showServerReply(client);
client.login("pwyrwinski", "secret");
showServerReply(client);
System.out.println("Current working directory is: " + client.printWorkingDirectory());
String someDirectory = "nonexistentDir";
client.makeDirectory("/" + someDirectory + "/Archive");
showServerReply(client);
client.logout();
showServerReply(client);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void showServerReply(FTPClient ftpClient) {
// ...
}
}
私のマシンでの結果:
SERVER: 220 (vsFTPd 2.3.5)
SERVER: 230 Login successful.
Current working directory is: "/home/pwyrwinski"
SERVER: 550 Create directory operation failed.
SERVER: 221 Goodbye.
そして、String someDirectory
「home/pwyrwinski」に変更したとき:
SERVER: 220 (vsFTPd 2.3.5)
SERVER: 230 Login successful.
Current working directory is: "/home/pwyrwinski"
SERVER: 257 "/home/pwyrwinski/Archive" created
SERVER: 221 Goodbye.
550
許可またはアクセス拒否のコードです。このコードやその他のコードは簡単にグーグルで検索できます。
これがお役に立てば幸いです。
ディレクトリを段階的に作成する必要があります。そうしないと、create directory false が表示されます。例を示します。http://www.codejava.net/java-se/networking/ftp/creating-nested-directory-structure-on-a-ftp-server