Implementing a FTP-Client in Java

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page.
Cheers. Eugen

1. Overview

In this tutorial, we’ll take a look at how to leverage the Apache Commons Net library to interact with an external FTP server.

2. Setup

When using libraries, that are used to interact with external systems, it’s often a good idea to write some additional integration tests, in order to make sure, we’re using the library correctly.

Nowadays, we’d normally use Docker to spin up those systems for our integration tests. However especially when used in passive mode, an FTP server isn’t the easiest application to run transparently inside a container if we want to make use of dynamic port mappings (which is often necessary for tests being able to be run on a shared CI server).

That’s why we’ll use MockFtpServer instead, a Fake/Stub FTP server written in Java, that provides an extensive API for easy use in JUnit tests:

We need the server address and the port, as well as the username and the password. After connecting it’s necessary to actually check the reply code, to be sure connecting was successful. We also add a PrintCommandListener, to print the responses we’d normally see when connecting to an FTP server using command line tools to stdout.

Since our integration tests will have some boilerplate code, like starting/stopping the MockFtpServer and connecting/disconnecting our client, we can do these things in the @Before and @After methods:

The implementation itself is equally straightforward. To make the returned data structure a bit simpler for the sake of this example, we transform the returned FTPFile array is transformed into a list of Strings using Java 8 Streams: