Implementing FTP Operations with Apache Commons Net in Java

Apache Commons Net FTPClient Dependency

Apache Commons Net provides a comprehensive FTP client implementation for Java applications through its FTPClient class. This library enables developers to perform various file transfer operations with FTP servers.

Maven Configuration

Add the following dependency to your project's pom.xml file:

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

Gradle Configuration

For Gradle projects, include this dependency in your build.gradle file:

implementation 'commons-net:commons-net:3.8.0'

Basic FTP File Upload Implementation

import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;

public class FileTransferService {
    public static void uploadFile() {
        FTPClient client = new FTPClient();
        FileInputStream fileStream = null;
        
        try {
            client.connect("ftp.server.com", 21);
            client.login("user", "pass123");
            
            fileStream = new FileInputStream("document.pdf");
            boolean success = client.storeFile("backup.pdf", fileStream);
            
            if (success) {
                System.out.println("File uploaded successfully");
            }
            
            client.logout();
        } catch (IOException e) {
            System.err.println("Transfer error: " + e.getMessage());
        } finally {
            try {
                if (fileStream != null) fileStream.close();
                if (client.isConnected()) client.disconnect();
            } catch (IOException e) {
                System.err.println("Cleanup error: " + e.getMessage());
            }
        }
    }
}

Core FTPClient Capabilities

The FTPClient class supports numerous operations including direcotry listing, file deletion, directory creation, and file retrieval. It handles both active and passive connection modes and supports various data encoding formats.

Tags: java FTP apache-commons file-transfer network-programming

Posted on Tue, 21 Jul 2026 17:16:51 +0000 by pup200