When programming FTP in Java using the Apache Commons Net API, we can obtain messages replied from a FTP server after each command sent by a FTP client. To do so, call either of the following two methods from the FTPClientclass:
ftpClient.login(user, pass); String serverReply = ftpClient.getReplyString(); System.out.println(serverReply);
ftpClient.changeWorkingDirectory("/photos"); String[] replies = ftpClient.getReplyStrings(); if (replies != null && replies.length > 0) { for (String aReply : replies) { System.out.println("SERVER: " + aReply); } }
Here’s an example program that connects and logins to a FTP server, then logouts and disconnects. The server’s response is displayed after each command using the getReplyString()method:
package net.codejava.ftp; import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; /** * This program demonstrates how to get and display reply messages from * a FTP server. * @author www.codejava.net * */ public class FTPGetServerReplyDemo { public static void main(String[] args) { String server = "www.myserver.com"; int port = 21; String user = "username"; String pass = "password"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); System.out.println(ftpClient.getReplyString()); ftpClient.login(user, pass); System.out.println(ftpClient.getReplyString()); ftpClient.logout(); System.out.println(ftpClient.getReplyString()); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } } } } }
And here’s the sample output when running the above program:
220---------- Welcome to Pure-FTPd [privsep] [TLS] ---------- 220-You are user number 12 of 50 allowed. 220-Local time is now 06:02. Server port: 21. 220 You will be disconnected after 15 minutes of inactivity. 230 OK. Current restricted directory is / 221-Goodbye. You uploaded 0 and downloaded 0 kbytes. 221 Logout.