In Java FTP programming with Apache Commons Net API, to know details of a file or directory such as size and last modified date (timestamp) from a FTP server, we can use the mlistFile() method of the FTPClient class as follows:

FTPFile ftpFile = ftpClient.mlistFile(remoteFilePath);

Where remoteFilePath is a String represents path of the file or directory (can be relative or absolute to the user’s home directory on the server). If the specified file/directory exists, the method returns a FTPFile object, otherwise it returns null. Then we can use some getter methods of the FTPFile class to get desired information as follows:

The following is code of an example program that logins to a FTP server then gets details of a file using the mlistFile() method:

package net.codejava.ftp;

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
 * An example program that demonstrates how to get details of a file and
 * directory from a FTP server using Apache Commnons Net API.
 * @author www.codejava.net
 *
 */
public class FTPGetFileDetails {

	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);
			ftpClient.login(user, pass);

			// use local passive mode to pass firewall
			ftpClient.enterLocalPassiveMode();

			// get details of a file or directory
			String remoteFilePath = "Java/CodeLib/FTP.rar";

			FTPFile ftpFile = ftpClient.mlistFile(remoteFilePath);
			if (ftpFile != null) {
				String name = ftpFile.getName();
				long size = ftpFile.getSize();
				String timestamp = ftpFile.getTimestamp().getTime().toString();
				String type = ftpFile.isDirectory() ? "Directory" : "File";

				System.out.println("Name: " + name);
				System.out.println("Size: " + size);
				System.out.println("Type: " + type);
				System.out.println("Timestamp: " + timestamp);
			} else {
				System.out.println("The specified file/directory may not exist!");
			}

			ftpClient.logout();
			ftpClient.disconnect();

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
} 

Here’s the output when running the above program:

Name: Java/CodeLib/FTP.rar
Size: 13021440
Type: File
Timestamp: Sat Jul 13 13:11:04 ICT 2013 

 

API References:

 

Related Java FTP Tutorials:

 

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 (FTPGetFileDetails.java)FTPGetFileDetails.java[Java FTP get file details example program]1 kB