What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A Java FTP client built with Apache Commons Net 3.13.0 can connect to an FTP server, authenticate, list directories, upload and download files, and delete or rename remote files. Use FTPClient for plain FTP, FTPSClient for FTP over TLS, and a separate SSH library when the server requires SFTP.

This guide uses a defensive baseline: validate the connection reply, configure timeouts, enter local passive mode after connecting, select binary transfer mode explicitly, check Boolean operation results, complete streamed transfers, and always disconnect in cleanup.

Key takeaways

  • Apache Commons Net 3.13.0 is the current verified release as of August 18, 2026, and it requires Java 8 or later.
  • FTPClient implements FTP, while FTPSClient implements FTP over TLS; Commons Net’s FTP package does not implement SFTP.
  • For ordinary client-to-server transfers, enter local passive mode and set FTP.BINARY_FILE_TYPE after connecting.
  • storeFile and retrieveFile return boolean, so failed operations require inspection of getReplyCode() and getReplyString().
  • Stream-based methods such as storeFileStream and retrieveFileStream require completePendingCommand() after the data stream closes.
  • Production workflows should upload under a temporary name and rename the completed file rather than exposing a partially uploaded final filename.

What is Apache Commons Net used for in Java FTP clients?

Apache Commons Net is an Apache-licensed Java networking library that provides protocol-level clients for FTP and FTPS as well as SMTP, POP3, IMAP, Telnet, NNTP, NTP, and other protocols. This article focuses on its FTP package and the classes needed for file-transfer integrations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The central FTPClient class manages FTP’s control connection and data connections. The class exposes protocol operations and configuration rather than a complete synchronization, scheduling, monitoring, or guaranteed-delivery platform. That low-level control works well for vendor feeds, scheduled batch jobs, internal transfers, and custom application workflows, provided the application supplies lifecycle management, retries, integrity checks, and operational logging.

#1 Best Overall
Sale
TP-Link USB to Ethernet Adapter,Support Nintendo Switch,1Gbps,Plug and Play
  • 𝐇𝐢𝐠𝐡-𝐒𝐩𝐞𝐞𝐝 𝐔𝐒𝐁 𝐄𝐭𝐡𝐞𝐫𝐧𝐞𝐭 𝐀𝐝𝐚𝐩𝐭𝐞𝐫 - UE306 is a USB 3.0 Type-A to RJ45 Ethernet adapter that adds a reliable wired network port to your laptop, tablet, or Ultrabook. It delivers fast and stable 10/100/1000 Mbps wired connections to your computer or tablet via a router or network switch, making it ideal for file transfers, HD video streaming, online gaming, and video conferencing.
  • 𝐔𝐒𝐁 𝟑.𝟎 𝐟𝐨𝐫 𝐅𝐚𝐬𝐭𝐞𝐫, 𝐌𝐨𝐫𝐞 𝐒𝐭𝐚𝐛𝐥𝐞 𝐃𝐚𝐭𝐚 𝐓𝐫𝐚𝐧𝐬𝐟𝐞𝐫𝐬- Powered via USB 3.0, this adapter provides high-speed Gigabit Ethernet without the need for external power(10/100/1000Mbps). Backward compatible with USB 2.0/1.1, it ensures reliable performance across a wide range of devices.
  • 𝐒𝐮𝐩𝐩𝐨𝐫𝐭𝐬 𝐍𝐢𝐧𝐭𝐞𝐧𝐝𝐨 𝐒𝐰𝐢𝐭𝐜𝐡- Easily connect your Nintendo Switch to a wired network for faster downloads and a more stable online gaming experience compared to Wi-Fi.
  • 𝐏𝐥𝐮𝐠 𝐚𝐧𝐝 𝐏𝐥𝐚𝐲- No driver required for Nintendo Switch, Windows 11/10/8.1/8, and Linux. Simply connect and enjoy instant wired internet access without complicated setup.
  • 𝐁𝐫𝐨𝐚𝐝 𝐃𝐞𝐯𝐢𝐜𝐞 𝐂𝐨𝐦𝐩𝐚𝐭𝐢𝐛𝐢𝐥𝐢𝐭𝐲- Supports Nintendo Switch, PCs, laptops, Ultrabooks, tablets, and other USB-powered web devices; works with network equipment including modems, routers, and switches.

The official Apache Commons Net project overview describes the broader protocol scope. The FTP-specific API is documented in the FTPClient API reference.

Class Purpose
FTPClient Plain FTP connections and file-transfer commands.
FTPSClient FTP with TLS, using explicit or implicit TLS modes.
FTPFile Parsed metadata for a remote file or directory.
FTPClientConfig Server-specific listing parser, locale, date, and format configuration.
FTPReply Reply-code constants and helpers such as positive-completion checks.
FTP FTP constants, including binary and ASCII file types.
FTPConnectionClosedException A more specific exception for a server-side connection close, commonly associated with reply code 421.

How do you install Apache Commons Net?

Use Apache Commons Net version 3.13.0 in Maven or Gradle. The release was published on March 15, 2026, and the project requires Java 8 or later according to the official download page and dependency information.

Maven

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

Gradle

implementation("commons-net:commons-net:3.13.0")

Commons Net is distributed under the Apache License 2.0. Ordinary FTP client use normally does not require adding Commons IO manually because the current project dependency information declares Commons IO as a compile dependency. Recheck the official release history before pinning a new application release, because 3.13.0 is the latest version verified for this article rather than a permanent promise about future releases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How does the FTP connection lifecycle work?

An FTP session has a control connection for commands and replies and separate data connections for listings and file contents. A reliable client constructs the object, configures timeouts, connects, validates the server reply, authenticates, selects passive mode and transfer type, performs operations, logs out, and disconnects even when an exception occurs.

Connecting alone does not prove that the server accepted the session. The FTPClient API documentation requires a connection before normal FTP operations and provides reply accessors for validating the result.

A safe baseline connection

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

import java.io.IOException;

public final class FtpConnectionExample {
    public static void main(String[] args) {
        String host = "ftp.example.com";
        int port = 21;
        String username = System.getenv("FTP_USERNAME");
        String password = System.getenv("FTP_PASSWORD");

        FTPClient ftp = new FTPClient();

        try {
            ftp.setConnectTimeout(10_000);
            ftp.setDefaultTimeout(10_000);
            ftp.setDataTimeout(30_000);

            ftp.connect(host, port);

            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("FTP server rejected connection: "
                        + ftp.getReplyString());
            }

            if (!ftp.login(username, password)) {
                throw new IOException("FTP login failed: "
                        + ftp.getReplyString());
            }

            // Set these after connect: connect resets transfer-related state.
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            System.out.println("Connected to " + ftp.getSystemName());

            if (!ftp.logout()) {
                throw new IOException("FTP logout failed: "
                        + ftp.getReplyString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ignored) {
                    // Log this in a real application.
                }
            }
        }
    }
}

Do not hard-code production passwords in source code. Inject credentials from environment variables, a secret manager, or application configuration with appropriate access controls. The example uses placeholders and environment variables for that reason.

FTPClient is not normally used as an AutoCloseable resource, so Java try-with-resources is not the ordinary cleanup pattern. Explicit logout() is useful after successful work, but disconnect() belongs in guaranteed cleanup because logout itself can fail or an earlier operation can throw.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you upload a file with FTPClient?

Use storeFile(remotePath, inputStream) for a straightforward upload, close the input stream in the caller, and check the returned Boolean. The FTPClient API does not close an input stream supplied to storeFile.

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

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public static void upload(FTPClient ftp, Path localFile, String remotePath)
        throws IOException {
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    try (InputStream input = Files.newInputStream(localFile)) {
        boolean uploaded = ftp.storeFile(remotePath, input);
        if (!uploaded) {
            throw new IOException("Upload failed: " + ftp.getReplyString());
        }
    }
}

Binary mode is the safe default for archives, images, PDFs, executables, and most application data. Use ASCII mode only when the receiving workflow explicitly expects NETASCII text conversion. Commons Net documents ASCII as the default file type, and a connect method resets the file type to ASCII, so set binary mode after connecting even if code appears to set it earlier.

How do you upload large files or report progress?

Use storeFileStream when the application needs to copy the stream itself, measure progress, or integrate with a custom stream pipeline. A streamed FTP command is not complete merely because the data stream has been closed.

Rank #2
Amazon Basics USB 3.0 to 10/100/1000 Gigabit Ethernet Internet Adapter, Compatible with Windows and macOS, Black
  • Connects a USB 3.0 device (computer/laptop) to a router, modem, or network switch to deliver Gigabit Ethernet to your network connection. Does not support Smart TV or gaming consoles (e.g.Nintendo Switch).
  • Supported features include Wake-on-LAN function, Green Ethernet & IEEE 802.3az-2010 (Energy Efficient Ethernet)
  • Supports IPv4/IPv6 pack Checksum Offload Engine (COE) to reduce Cental Processing Unit (CPU) loading
  • Compatible with Windows 8.1 or higher, Mac OS
import java.io.OutputStream;

try (InputStream input = Files.newInputStream(localFile);
     OutputStream output = ftp.storeFileStream(remotePath)) {

    if (output == null) {
        throw new IOException("Could not open remote data stream: "
                + ftp.getReplyString());
    }

    input.transferTo(output);
}

if (!ftp.completePendingCommand()) {
    throw new IOException("FTP server did not complete upload: "
            + ftp.getReplyString());
}

Call completePendingCommand() after the output stream closes. Omitting that call can leave the control connection out of sync, making the next command fail even though the data copy appeared to finish.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you prevent consumers from reading a partial upload?

Upload to a temporary remote name, validate the transfer, and rename the temporary file to its final name only after completion. Remote rename is not a universal transaction across servers, but it is a practical handoff convention when the server supports it.

String temporaryRemotePath = "/incoming/orders.csv.part";
String finalRemotePath = "/incoming/orders.csv";

upload(ftp, localFile, temporaryRemotePath);

// Add a size or checksum verification step when the server supports it.
if (!ftp.rename(temporaryRemotePath, finalRemotePath)) {
    throw new IOException("Remote rename failed: " + ftp.getReplyString());
}

Also define what should happen after a timeout: the application may need to inspect, remove, or resume the temporary file. Duplicate delivery, overwriting, and replay behavior should be explicit in a batch workflow.

How do you download a file with FTPClient?

Use retrieveFile(remotePath, outputStream) for a complete download and check its Boolean result before treating the local file as valid.

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

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public static void download(FTPClient ftp, String remotePath, Path localFile)
        throws IOException {
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    try (OutputStream output = Files.newOutputStream(localFile)) {
        boolean downloaded = ftp.retrieveFile(remotePath, output);
        if (!downloaded) {
            throw new IOException("Download failed: " + ftp.getReplyString());
        }
    }
}

For safer processing, download to a local temporary path, verify the size or content, and move the file into the application’s processing directory only after validation. Downloaded files are untrusted input: validate their size, expected type, and content before parsing or executing anything.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you stream a download?

Use retrieveFileStream when the application needs direct control over the data stream, and call completePendingCommand() after both streams close.

try (InputStream input = ftp.retrieveFileStream(remotePath);
     OutputStream output = Files.newOutputStream(localFile)) {

    if (input == null) {
        throw new IOException("Could not open remote data stream: "
                + ftp.getReplyString());
    }

    input.transferTo(output);
}

if (!ftp.completePendingCommand()) {
    throw new IOException("FTP server did not complete download: "
            + ftp.getReplyString());
}

If the stream method returns null, no usable data stream was opened. If the final completion call returns false, the server rejected or failed the command after the preliminary data-channel response. Both cases require the reply code and reply text in logs.

How do you list FTP files and navigate directories?

Use listFiles(path) when you need parsed metadata and listNames(path) when you need only names. Commons Net represents parsed entries as FTPFile objects.

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

FTPFile[] files = ftp.listFiles("/incoming");

for (FTPFile file : files) {
    System.out.printf("%s %s %d%n",
            file.isDirectory() ? "DIR " : "FILE",
            file.getName(),
            file.getSize());
}

String[] names = ftp.listNames("/incoming");
System.out.println("Names returned: " + (names == null ? 0 : names.length));

Common directory and metadata operations include:

String current = ftp.printWorkingDirectory();
boolean changed = ftp.changeWorkingDirectory("/incoming");
boolean parent = ftp.changeToParentDirectory();
boolean made = ftp.makeDirectory("/archive");
boolean removed = ftp.removeDirectory("/empty-directory");
boolean deleted = ftp.deleteFile("/incoming/file.txt");
String modificationTime = ftp.getModificationTime("/incoming/file.txt");

Where the server supports the relevant command, mdtmFile(path) can provide modification-time information. Check every Boolean result and do not assume that a server account has permission to create, delete, rename, or navigate every path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why can FTP directory listings fail even when login works?

FTP directory listings use a data connection and server-specific output formats, so successful authentication does not guarantee that listFiles will work. Server operating system, locale, date format, command support, and nonstandard formatting can all affect parsing.

Rank #3
BENFEI USB 3.0 to Ethernet Adapter, USB C to RJ45 Gigabit LAN (1000Mbps) Network Adapter, Compatible with MacBook/Pro/Air, Surface Pro, Windows 11/10/8/7, Mac OS [Aluminium Shell&Nylon Cable]
  • COMPACT DESIGN - The compact-designed portable BENFEI USB A/C to Ethernet adapter connects your computer or tablet to a router,modem or network switch for network connection. It adds a standard RJ45 port to your Ultrabook, notebook or Macbook Air for file transferring, video conferencing, gaming, and HD video streaming.
  • SUPERIOR STABILITY - Built-in advanced IC chip works as the bridge between RJ45 Ethernet cable and your USB A/C devices. The driver-free installation with native driver support in Chrome, Mac, and Windows OS; The USB A/C Ethernet adapter dongle supports important performance features including Wake-on-Lan (WoL), Full-Duplex (FDX) and Half-Duplex (HDX) Ethernet, Crossover Detection, Backpressure Routing, Auto-Correction (Auto MDIX).
  • INCREDIBLE PERFORMANCE - Supports full 10/100/1000Mbps gigabit ethernet performance over USB A/C's 5Gbps bus, faster and more reliable than most wireless connections. Link and Activity LEDs. USB powered, no external power required. Backward compatible with USB 2.0/1.1.✅ To reach 1Gbps, make sure to use CAT6 & up Ethernet cables.
  • BROAD COMPATIBILITY - The USB A/C-Ethernet adapter is compatible with Windows 11/10/8.1/8/7/Vista/XP, Mac OSX 10.6/10.7/10.8/10.9/10.10/10.11/10.12, Linux kernel 3.x/2.6, Android and Chrome OS.Compatible with IEEE 802.3, IEEE 802.3u and IEEE 802.3ab. Supports IEEE 802.3az (Energy Efficient Ethernet).❌Do Not Support Windows RT. (NOT compatible with Nintendo Switch.)
  • 18 MONTH WARRANTY - Exclusive BENFEI Unconditional 18-month Warranty ensures long-time satisfaction of your purchase; Friendly and easy-to-reach customer service to solve your problems timely.

Commons Net provides parser support and FTPClientConfig for listing configuration. A localized or unusual LIST response may still require explicit configuration or a custom parser. The 3.13.0 release notes specifically record a fix involving Linux vsftpd listings in Chinese or Japanese locales.

Prefer machine-oriented listing commands such as MLSD or MLST when the server supports them and the application needs stable metadata. Do not treat all server listings as interchangeable, and test against the actual vendor endpoint rather than only a local FTP server.

What is the difference between passive and active FTP?

Active FTP asks the server to connect back to the client for the data connection, while passive FTP asks the client to connect to a server-advertised data port. Passive mode is generally easier for clients behind NAT devices and firewalls, but it requires the server’s passive port range, advertised address, and firewall rules to be correct.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ftp.enterLocalPassiveMode();

Call enterLocalPassiveMode() after connecting. Commons Net resets the data mode to active when a connect method is called, so selecting passive mode before connect() is insufficient.

Mode Data connection direction Typical client-side concern
Active Server connects back to the client. Inbound firewall and NAT rules commonly block the callback.
Local passive Client connects to the server’s advertised data port. Server passive range or NAT address may be misconfigured.
Remote passive/active Used for server-to-server transfers. Do not substitute these for ordinary client-to-server passive mode.

enterRemotePassiveMode() and enterRemoteActiveMode() are for server-to-server FTP operations. Ordinary applications downloading from or uploading to a server should normally use local passive mode.

How do you troubleshoot a bad PASV address?

If a passive transfer attempts to connect to a private or unroutable address, the server or its NAT device may be returning an unusable address in the PASV response. For IPv4, setUseEPSVwithIPv4(true) can allow EPSV to succeed by using only the port when the server’s PASV address is wrong.

ftp.setUseEPSVwithIPv4(true);
ftp.enterLocalPassiveMode();

The Commons Net FTPClient documentation also exposes passive-address and NAT-workaround settings. Use those settings deliberately: blindly trusting or replacing a server-supplied address can create a connection to the wrong host or conceal a server-side configuration error. The durable fix is usually to configure the server’s passive address and port range correctly and permit that range through the firewall.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you use FTPSClient for encrypted FTP?

Use FTPSClient when the provider offers FTP over TLS. Explicit FTPS commonly starts on the standard FTP control port and upgrades the connection with TLS; implicit FTPS is commonly associated with port 990. The provider’s documented endpoint and TLS mode are authoritative.

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;

import java.io.IOException;

FTPSClient ftps = new FTPSClient(false); // explicit TLS

try {
    ftps.setConnectTimeout(10_000);
    ftps.setDefaultTimeout(10_000);
    ftps.setDataTimeout(30_000);

    ftps.connect(host, 21);

    if (!ftps.login(username, password)) {
        throw new IOException("FTPS login failed: " + ftps.getReplyString());
    }

    ftps.execPBSZ(0);
    ftps.execPROT("P");
    ftps.enterLocalPassiveMode();
    ftps.setFileType(FTP.BINARY_FILE_TYPE);

    // Transfer files here.
} finally {
    if (ftps.isConnected()) {
        ftps.disconnect();
    }
}

Protecting the control connection is not enough if the data connection remains clear. PBSZ and PROT must match the server’s requirements; PROT P requests private data-channel protection.

FTPS is not automatically secure merely because the class is named FTPSClient. The FTPSClient API documentation warns that hostname verification is not enabled by default and exposes hostname-verifier and endpoint-checking controls. Production code should use a properly configured trust store and enable strict certificate and hostname validation. Do not use trust-all certificates or permissive hostname verifiers outside an isolated test environment.

Rank #4
Anker USB C to Ethernet Adapter, Portable 1 Gbps Network Hub
  • The Anker Advantage: Join the 65 million+ powered by our leading technology.
  • Instant Internet: Connect to the internet instantly from virtually any USB-C 3.0 device, and enjoy stable connection speeds of up to 1 Gbps.
  • Lightweight and Compact: The space-saving and portable design measures just over half an inch thick and weighs about the same as a AA battery.
  • Premium Build: Features a sleek aluminum exterior and braided-nylon cable to complement the design of high-end devices.
  • What You Get: PowerExpand USB-C to Gigabit Ethernet Adapter, welcome guide, 18-month worry-free warranty, and friendly customer service.

What is the difference between FTP, FTPS, and SFTP?

FTP, FTPS, and SFTP are different protocols with different security models and client implementations. Commons Net directly supports FTP and FTPS, not SFTP.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Protocol Security model Commons Net class Choose it when
FTP No encryption for credentials or data. FTPClient The endpoint is explicitly plain FTP and the network and data policy permit it.
FTPS FTP with TLS for the control and, when configured, data channels. FTPSClient An existing FTP service requires TLS.
SFTP SSH-based file transfer. Not provided by Commons Net’s FTP package. The provider supplies an SSH host, key, or SFTP endpoint.

If the provider gives an ftp:// endpoint, use FTPClient. If the provider gives FTP-with-TLS instructions, use FTPSClient. If the provider says SFTP or supplies SSH credentials, use an SSH-based SFTP library instead of adapting FTPClient. SFTP is not simply “secure FTP.”

How should you configure timeouts and keep-alives?

Configure connection, control-channel, and data-channel timeouts separately because a server can accept a connection quickly while a listing or large transfer stalls later.

ftp.setConnectTimeout(10_000); // Time allowed to establish the socket
ftp.setDefaultTimeout(10_000); // Default control-channel timeout
ftp.setDataTimeout(30_000);    // Data-channel connect/read timeout
Setting What it limits Typical symptom when too short
Connect timeout Establishing the control socket. Slow or distant server appears unreachable.
Default timeout Waiting for control-channel responses. Login or command appears to hang.
Data timeout Opening or reading a listing or transfer data connection. Listing or file transfer fails while login works.
Application job timeout The entire business operation. A stuck transfer consumes a scheduler or worker indefinitely.

For long transfers or control connections that remain idle, Commons Net provides setControlKeepAliveTimeout and setControlKeepAliveReplyTimeout. These settings can help with routers or servers that mishandle idle connections, as noted in the Commons Net release history. Keep-alives do not repair a blocked data port, and timeout values should reflect the slowest expected server rather than an ideal local network.

How do you handle FTP reply codes and failed operations?

Inspect both the numeric reply code and text whenever an operation fails. Commons Net methods often return false instead of throwing an exception for an FTP-level rejection.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
int code = ftp.getReplyCode();
String text = ftp.getReplyString();

if (!ftp.deleteFile("/incoming/file.txt")) {
    throw new IOException("Delete failed; FTP reply "
            + code + ": " + text);
}

Separate Java-side transport failures from server replies. An IOException can indicate a socket, timeout, or stream problem. A failed login can indicate bad credentials, account restrictions, or an authentication-policy mismatch. A failed file operation can indicate a missing path, permissions, quota, name collision, or a data-channel failure.

Symptom Likely cause Diagnostic or recovery
Login returns false Bad credentials or account restriction. Log the reply code and message without logging the password; verify server policy.
Connect succeeds but listing hangs Data channel blocked. Use local passive mode; check the server passive range and firewall.
Passive transfer targets a private IP Broken NAT or PASV configuration. Try EPSV where appropriate and correct server NAT configuration.
Upload or download returns false Permission, path, quota, or server transfer error. Inspect getReplyCode() and getReplyString().
First streamed transfer works but the second fails Missing completePendingCommand(). Call it after closing the data stream.
Server disconnects during idle time Server or intermediary timeout, often reply 421. Use keep-alives where suitable or reconnect at a safe retry boundary.
FTPS handshake fails Trust-store, protocol, or hostname mismatch. Use a valid trust store and strict hostname validation; inspect TLS diagnostics.
FTPS login works but transfer fails Data-channel protection mismatch. Configure PBSZ and PROT according to the server.

A preliminary positive response does not replace the final completion response. This is why streamed methods need an explicit completion call and why the reply should be recorded at the point of failure.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do you handle encoding and non-ASCII FTP filenames?

FTP control-channel encoding and directory-listing parsing affect filenames containing non-ASCII characters. Enable UTF-8 autodetection only when the server correctly advertises or supports UTF-8 rather than assuming that every FTP server does.

ftp.setAutodetectUTF8(true);

When filenames are garbled or listings cannot be parsed, verify the server’s advertised encoding, the client control encoding, and the listing parser configuration. Use FTPClientConfig for server-specific locale, date, and listing-format settings. A custom parser may be necessary for a genuinely nonstandard listing. Test names containing the actual languages and characters used by the vendor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do resume and atomic transfer patterns work?

Commons Net exposes restart support, including setRestartOffset(offset), but resume behavior depends on server support and must be validated with the actual endpoint. A restart offset does not by itself prove that the remote file and local file have matching content up to that point.

Best Value
Acer USB to Ethernet Adapter, USBC Hub Ethernet 1Gbps with 3*USB 3.0
  • Dual USB-A/C Port Design: This USB hub with ethernet adapter features dual connectors for both USB C and USB A devices, ensuring wide compatibility across laptops, tablets, and smartphones. It includes 1x Gigabit Ethernet port and 3x USB A 3.0 ports, all usable at the same time for smooth and efficient connectivity. 📌Note: When using USB-A to connect devices, please ensure the USB-C is securely attached to the USB-A connector.
  • Stable Gigabit Ethernet Adapter: Get fast, wired Internet up to 1000Mbps with this USB C to ethernet adapter. Backward compatible with 10/100Mbps networks for flexible connectivity across various setups. Ideal for streaming, gaming, and large file transfers. 📌Note: Ensure the RJ45 connector is plugged in securely in the port and use CAT6 & above Ethernet cable is required to reach 1 Gbps.
  • 5Gbps Data Transfer: Transfer large files, photos, and videos in seconds with this USB 3.0 hub supporting speeds up to 5Gbps—10× faster than USB 2.0. Backward compatible with USB 2.0 and 1.1 devices, this USB splitter expands one port into three for connecting keyboards, mice, and flash drives for everyday use. 📌Note: The three USB-A 3.0 ports share a total 5Gbps bandwidth.【NO HDMI port, NO USB-C data port, and NO PD charging】
  • Plug and Play: Reliable USB to ethernet adapter ready to use in seconds. Instantly connects with USB-A and USB-C devices including MacBook Pro/Air, iPad Pro, iMac, Surface Laptops, Chromebook, XPS, tablets, Steam, and smartphones. Works with Windows, macOS, Linux, Chrome OS, and Android. 📌XP/Win7 may need driver. Older systems may not recognize this product due to its USB 3.0 chip. Please refer to the “Installation Manual” to manually download and install the driver.
  • Durable & Portable Build: Made with sturdy aluminum alloy, this RJ45 to USB-C adapter delivers long-term durability, efficient heat dissipation, and stable performance for offices, corporate deployments, classrooms, and campus workstations—while its slim, portable form factor makes it ideal for business travel, educators, and mobile professionals.

For reliable batch delivery, use this sequence:

  1. Upload to a temporary remote filename.
  2. Complete the transfer and check the final FTP reply.
  3. Verify size or checksum when the server supports a suitable command.
  4. Rename the temporary file to the final name.
  5. Make downstream consumers ignore temporary suffixes such as .part.

Retries should be designed around idempotency. A retry after an uncertain timeout may create a duplicate or overwrite an existing file, so choose naming, overwrite, resume, and cleanup rules deliberately.

What security practices should a production FTP client follow?

  • Prefer FTPS or SFTP over plain FTP when credentials or file contents must be protected in transit.
  • Never hard-code production credentials; use a secret manager, environment variables, or injected configuration.
  • Validate FTPS certificate chains and hostnames with a controlled trust store.
  • Use least-privilege server accounts restricted to the required directories and commands.
  • Restrict application paths to the intended remote directory and guard against unintended overwrites.
  • Do not log passwords, secrets, or sensitive filenames.
  • Set connection, control, data, and overall job timeouts.
  • Treat downloaded files as untrusted input and validate size, type, and content before processing.
  • Use temporary names and final renames for files consumed by another process.
  • Define duplicate-delivery, replay, timeout, and partial-file cleanup behavior.

Plain FTP sends credentials and data without encryption. Port 21 normally identifies standard FTP or explicit FTPS negotiation; implicit FTPS is commonly associated with port 990, but the server’s configuration is authoritative. A port number alone is not proof that a session is encrypted.

When should you choose SFTP, an integration framework, or managed MFT?

Apache Commons Net is a good fit when the application needs direct FTP or FTPS access, custom protocol control, and a mature Apache-licensed dependency. The application team must still implement lifecycle handling, retries, logging, integrity checks, and workflow semantics.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an SSH-based SFTP library when the endpoint is SFTP. Choose Apache Camel or a similar integration framework when the requirement includes scheduled routes, polling, retries, moves, monitoring, and broader enterprise integration patterns. Choose a managed file-transfer platform when centralized auditing, partner onboarding, key management, alerting, policy enforcement, or regulated delivery matters more than embedding a low-level client. Frameworks and platforms add operational capabilities but also add configuration, infrastructure, and sometimes licensing complexity.

Requirement Appropriate direction Trade-off
Custom FTP or FTPS commands inside a Java service Apache Commons Net More application code for retries, monitoring, and integrity.
SSH-based endpoint SFTP-capable SSH library Different protocol and authentication model.
Scheduled polling and routed transfers Integration framework More abstraction and configuration.
Central governance and partner operations Managed MFT platform Additional infrastructure or licensing and less low-level control.

Production checklist

  • Pin and periodically review the Commons Net version; 3.13.0 is the latest version verified for this article on August 18, 2026.
  • Confirm whether the endpoint is FTP, explicit FTPS, implicit FTPS, or SFTP.
  • Validate the connection reply before logging in.
  • Configure connect, control, data, and job-level timeouts.
  • Enter local passive mode after connecting.
  • Set binary mode after connecting unless the workflow explicitly requires ASCII.
  • Check every Boolean operation result and include reply code and text in safe diagnostics.
  • Call completePendingCommand() after every stream-based upload or download.
  • Test passive port ranges, NAT addresses, TLS certificates, locales, and representative filenames against the real server.
  • Use temporary remote names, verification, and final rename for downstream handoffs.
  • Disconnect in guaranteed cleanup and define safe retry and reconnection boundaries.

Frequently Asked Questions

Does Apache Commons Net support SFTP?

No. Apache Commons Net provides FTP through FTPClient and FTP over TLS through FTPSClient; SFTP is an SSH-based protocol and requires a separate SFTP-capable SSH library.

Why must passive mode be enabled after connect()?

Calling a Commons Net connect method resets the FTP data mode to active. Call enterLocalPassiveMode() after connecting so ordinary client-to-server listings and transfers use passive mode.

Why is completePendingCommand() necessary?

Stream-based methods such as retrieveFileStream and storeFileStream leave the FTP command transaction pending after the data stream closes. Calling completePendingCommand() reads the final server response and keeps the control connection synchronized.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is FTPS secure by default in Apache Commons Net?

FTPS encrypts FTP with TLS, but production security still requires a valid trust configuration and hostname verification. The FTPSClient API documents that hostname verification is not enabled by default, so applications must configure and test it explicitly.

What file type should a Java FTP client use?

Use FTP.BINARY_FILE_TYPE for binary files and most automated application transfers. Use FTP.ASCII_FILE_TYPE only when the remote workflow specifically requires NETASCII text conversion, and set the type after connecting.

The Bottom Line

Apache Commons Net is a practical low-level Java FTP and FTPS client when the application needs direct control over file transfers. The safe baseline is to validate replies, use timeouts and passive mode, set binary mode after connecting, close streams correctly, complete pending commands, protect FTPS certificates and hostnames, and publish completed files through a temporary-name-and-rename workflow. Use an SFTP library for SFTP endpoints and a higher-level integration or managed MFT platform when the requirement extends beyond protocol operations.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.