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 a 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.example.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.org");

            // When login success the login method returns true.
            boolean login = client.login("admin", "admin123**");
            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

<!-- http://repo1.maven.org/maven2/commons-net/commons-net/3.6/commons-net-3.6.jar -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

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.

Leave a Reply