Although the Apache Commons Net API does not provide a direct method for getting size of a file on FTP server, there are two indirect methods which we can employ to query size of the remote file:
Following are examples for the two methods above.
Using mlistFile() method:
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(); } } } } }
To test the program, remember to replace the connection settings with yours.