Pages Navigation Menu

Coding is much easier than you think

Get all file size on FTP Server

 

FTPClient class does not provide any direct method to find the size of file. So we will use another way to list the file size. FTPFile class provide you method getSize() to get the size of the current file.

FTPFile class handles files stored on FTP server. It shows you different information about the files.

long getSize() : This method returns size of file in bytes. Its return type is long.

Example :

In this example, we are listing all files and their size. For that first list all files and store it in FTPFile array. Now iterate and check if it is file by usinf method isFile() then get its name using method getName()(as file.getName()) and get its size using method getSize() (as file.getSize()).

Here is complete source code –
 
** UPDATE: FTP Complete tutorial now available here.
 
FtpFileSize.java
 

package com.simplecode.net;

import java.io.IOException;

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

class FtpFileSize {
	public static void main(String[] arg) throws IOException {
		FTPClient ftpClient = new FTPClient();
		boolean result;
		try {

			// Connect to the localhost
			ftpClient.connect("localhost");

			// login to ftp server
			result = ftpClient.login("admin", "admin");

			if (result == true) {
				System.out.println("User logged in successfully !");
			} else {
				System.out.println("Login failed !");
				return;
			}

			FTPFile[] files = ftpClient.listFiles();
			System.out.println("Files and their size on Ftp Server : ");
			for (FTPFile file : files) {
			if (file.isFile()) {
			     System.out.print("File name : " + file.getName());
			     System.out.print("\t size : " + file.getSize() + " Bytes");
			     System.out.println();
			}
			}

		} catch (FTPConnectionClosedException e) {
			System.err.println(e);
		} finally {
			try {
				ftpClient.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.err.println(e);
			}
		}
	}
}