FTPClient ftpClient = new FTPClient();
// code to connect and login....
String filePath = "/photos/mywedding.jpg";
FTPFile file = ftpClient.mlistFile(filePath);
long size = file.getSize();
System.out.println("File size = " + size);The output would be:File size = 2755863
Sending SIZE command:FTPClient ftpClient = new FTPClient();
// code to connect and login....
String filePath = "/photos/mywedding.jpg";
ftpClient.sendCommand("SIZE", filePath);
String reply = ftpClient.getReplyString();
System.out.println("Reply for SIZE command: " + reply);The output would be:Reply for size command: 213 2755863
Note that the reply string contains a FTP reply code (which is 213 – file status) then followed by the file size (separated by a space).To demonstrate, we created a small program that connects to a FTP server and employs the two mentioned methods to retrieve file size. Here’s the code:package net.codejava.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
/**
 * This program demonstrates how to get size of a particular file on a
 * FTP server, using Apache Commons Net API.
 * @author www.codejava.net
 *
 */
public class FTPFileSize {
	public static void main(String[] args) {
		String server = "www.yourserver.com";
		int port = 21;
		String user = "your_username";
		String pass = "your_password";
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.connect(server, port);
			ftpClient.login(user, pass);
			String filePath = "/photos/mywedding.jpg";
			FTPFile file = ftpClient.mlistFile(filePath);
			long size = file.getSize();
			System.out.println("File size = " + size);
			ftpClient.sendCommand("SIZE", filePath);
			String reply = ftpClient.getReplyString();
			System.out.println("Reply for size command: " + reply);
			ftpClient.logout();
			ftpClient.disconnect();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.logout();
					ftpClient.disconnect();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
 Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.