How to Start FTP Programming with Java?

learn how to start ftp programming with java

Since the inception of the internet, there have been many technological advancements related to internet usage. One of them, which is quite important we must say, is FTP. The acronym is short for File Transfer Protocol. Since the 1990’s, it has been used for the sharing of files from one destination to another through an Internet connection. It has proven quite useful, and it’s no surprise that it’s withstood the test of time to be applied in many of our basic online applications today.

From simply sending an email, to delivering an online assignment; this is all possible due to FTP. Apart from FTP, there is also another important feature that we should define; and that is an FTP file server. In a simple definition, an FTP file server is somewhat like a shared hard drive that can be accessed by any computer in the world as long as it is connected to the internet.

So nearly every file that’s being transferred this very second, is using FTP programming. Quite amazing right? But that’s not all. The field has evolved so rapidly today, that we have certified FTP programmers all around us!

You might be interested in checking out some Java desktop applications examples so give it a go!

So How to Start FTP Programming with Java?

There are many ways to get started with FTP programming. However, most beginners usually fall victim to this trap. They use the Java networking API to write code that communicates directly with the API server. This is strongly discouraged because, in turn, you will spend long hours trying to comprehend the FTP protocol in the runtime environment, testing it, and fixing any bugs that may occur. It’s advisable to always pick up some libraries that are already set for FTP programming.

facts about ftp

And here, on our website, we have them available for you. So that you can save on time! That being said, FTP programming is a process that follows the following steps. So let’s get started with the first steps on writing java code for FTP file transfer.

1. Connectivity


The first step is connecting and login into an FTP server. In this example, we are using the Apache Commons Net library. You need to be sure that you have all the java ftps client; especially the commons-net-3.1.jar in the class-path. Now, the class org.apache.commons.net.ftp.FTPClient will provide the required APIs to have access to a server through an FTP protocol. In order to connect to a server, you can use the following procedure:

void connect(String server, int port)

Where the server can be an IP address, a host name, or a port number. After connection, you can use the following method to have access:

boolean login(String username, String password)
Login() returns true if you successfully login, and returns false if login is unsuccessful.

It is good practice to check the server’s reply code whenever each call of void such as connect() is used. And after each call, the server will have to return a message. Here is a complete code for server login:

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPConnectAndLoginDemo {
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
public static void main(String[] args) {
String server = "www.yourserver.net";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
} else {
System.out.println("LOGGED IN SERVER");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
}

After compiling the program, just run it and you are good to go!

2. Listing Directory and Content


ftpClient.makeDirectory(“/projects/java/ftp/demo”);

Sometimes when attempting to create a directory through an FTP server using the above method, you can get an error like this:

550 Can’t create directory: No such file or directory

ftp file server

image credit: me.me

We can remedy this problem by creating a utility class as shown below:

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
/**
* This utility class provides a method that creates a nested directory
* structure on a FTP server, based on Apache Commons Net library.
* @author www.codejava.net
*
*/
public class FTPUtil {
/**
* Creates a nested directory structure on a FTP server
* @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
* @param dirPath Path of the directory, i.e /projects/java/ftp/demo
* @return true if the directory was created successfully, false otherwise
* @throws IOException if any error occurred during client-server communication
*/
public static boolean makeDirectories(FTPClient ftpClient, String dirPath)
throws IOException {
String[] pathElements = dirPath.split("/");
if (pathElements != null && pathElements.length > 0) {
for (String singleDir : pathElements) {
boolean existed = ftpClient.changeWorkingDirectory(singleDir);
if (!existed) {
boolean created = ftpClient.makeDirectory(singleDir);
if (created) {
System.out.println("CREATED directory: " + singleDir);
ftpClient.changeWorkingDirectory(singleDir);
} else {
System.out.println("COULD NOT create directory: " + singleDir);
return false;
}
}
}
}
return true;
}
}

This method makeDirectories() goes across all the single elements of structure in order to modify the current working directory to the current path element.

Below is a test program that will result in multiple directories to be created in the structure:

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
/**
* This is a test program that demonstrates creating a nested directory
* structure on a FTP server.
* @author www.codejava.net
*
*/
public class FTPMakeNestedDirectoryTest {
public static void main(String[] args) {
String server = "www.codejava.net";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
// connect and login to the server
ftpClient.connect(server, port);
ftpClient.login(user, pass);
// use local passive mode to pass firewall
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
String dirPath = "/projects/java/ftp/demo/connect";
FTPUtil.makeDirectories(ftpClient, dirPath);
// log out and disconnect from the server
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Always remember to modify the server, user, and pass to compliment your FTP account.

That being said, FTP programming is a large subject that contains other categories such as uploading files to an FTP server, downloading files from the server, plus plenty of other important techniques; which are all available here. You can also learn more about java and SQL and how these two work together.

So get in touch with one of our professional developers today and don’t question yourself about how to start ftp programming with java anymore!