Sample code for 30+ languages & platforms
Java

Get a Remote FTP File's Size by Name

See more FTP Examples

Demonstrates the Chilkat Ftp2.GetSizeByName method, which returns the size in bytes of a named file in the current remote directory as a 32-bit integer. The only argument is the filename — a name, not a path. It returns -1 when the file is not found or the size cannot be obtained.

Background: This is the direct way to get one file's size when you already know its name, typically via a SIZE command — no full directory listing required. Because the result is 32-bit, it cannot represent files past about 2 GB; use GetSizeStrByName for large files. The argument must be a bare filename in the current directory, so ChangeRemoteDir to the right place first.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the Ftp2.GetSizeByName method, which returns the size in bytes of a named file in
    //  the current remote directory as a 32-bit integer.  The only argument is the filename (a name,
    //  not a path).

    CkFtp2 ftp = new CkFtp2();

    ftp.put_Hostname("ftp.example.com");
    ftp.put_Username("myFtpLogin");

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    ftp.put_Password("myPassword");

    success = ftp.Connect();
    if (success == false) {
        System.out.println(ftp.lastErrorText());
        return;
        }

    success = ftp.ChangeRemoteDir("public_html");
    if (success == false) {
        System.out.println(ftp.lastErrorText());
        return;
        }

    //  Returns -1 when the file is not found or the size cannot be obtained.  For files that may
    //  exceed 2 GB, use GetSizeStrByName (returns a decimal string).
    int fileSize = ftp.GetSizeByName("report.pdf");
    if (fileSize < 0) {
        System.out.println("File not found, or size unavailable.");
        return;
        }

    System.out.println("report.pdf is " + fileSize + " bytes");

    success = ftp.Disconnect();
    if (success == false) {
        System.out.println(ftp.lastErrorText());
        return;
        }
  }
}