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:

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.

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (FTPGetServerReplyDemo.java)FTPGetServerReplyDemo.java[Demo program]0.9 kB