How do I connect to FTP server?

The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network. The example below shows you how to connect to an FTP server.

In this example we are using the FTPClient class of the Apache Commons Net library. To connect to the server, we need to provide the FTP server name. Login to the server can be done by calling the login() method of this class with a valid username and password. To logout we call the logout() method.

Let’s try the code snippet below:

package org.kodejava.commons.net;

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

import java.io.IOException;

public class FTPConnectDemo {
    public static void main(String[] args) {
        FTPClient client = new FTPClient();

        try {
            client.connect("ftp.example.com");

            // When login success, the login method returns true.
            boolean login = client.login("demo", "password");
            if (login) {
                System.out.println("Login success...");

                // When logout success, the logout method returns true.
                boolean logout = client.logout();
                if (logout) {
                    System.out.println("Logout from FTP server...");
                }
            } else {
                System.out.println("Login fail...");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Closes the connection to the FTP server
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.10.0</version>
</dependency>

Maven Central

Wayan

2 Comments

    • You can simply use the textual representation of the IP address as the argument to the connect method. For example FTPClient.connect("127.0.0.1"). Or you can create an InetAddress object using InetAddress.getByName("127.0.0.1") and then pass this InetAddress as the argument to the connect method.

      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.