How to connect FTP with Java

Nithidol Vacharotayan
4 min readJan 26, 2024

--

Image by upklyak on Freepik

The purpose of FTP is to transfer large file sizes or large numbers of files through the internet.

FTP has protocols, such as FTP, SFTP, and FTPS, which have pros and cons. The developer can choose which to use, followed by the business of individual projects.

FTP is not secure, but if used specifically inside the local network or if the client's internet speed is poor and the client wants to download large files, the developer can use this protocol because FTP supports file resumes, which prevents the download of entire files when the connection is lost.

Sometimes, The developer is confused between FTPS and SFTP.

FTPS and SFTP are the same protocols?

What is different between FTPS and SFTP is the way they connect to the server.

FTPS and SFTP are secure and suitable for transferring files across the internet.

Let’s start with the FTP list, download, upload, rename and delete the file.

Add maven dependency.

<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.11.1</version>
</dependency>

Connect FTP or FTPS server.

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

private static final String FTP_SERVER = "127.0.0.1";
//Default FTPS port is 990
//Default FTP port is 21
private static final int FTP_PORT = 21;
private static final String FTP_USER = "nithidol.v";
private static final String FTP_PASSWORD = "password";

private void connect(){
FTPClient ftpClient = new FTPClient();
try {
// Connect to the FTP server
ftpClient.connect(FTP_SERVER, FTP_PORT);
ftpClient.login(FTP_USER, FTP_PASSWORD);

// Set file transfer type to binary
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Disconnect from the FTP server
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

List files from the FTP server.

private static void listFiles(FTPClient ftpClient) throws IOException {
System.out.println("Listing files on the FTP server:");
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
System.out.println(file.getName());
}
}

Download the file from the FTP server.

private void downloadFile(FTPClient ftpClient, String remoteFilePath, String localFilePath) throws IOException {
File localFile = new File(localFilePath);
OutputStream outputStream = new FileOutputStream(localFile);
ftpClient.retrieveFile(remoteFilePath, outputStream);
System.out.println("File downloaded successfully.");
}

Upload the file from the FTP server.

private void uploadFile(FTPClient ftpClient, String localFilePath, String remoteFilePath) throws IOException {
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
ftpClient.storeFile(remoteFilePath, inputStream);
System.out.println("File uploaded successfully.");
}

Rename the file from the FTP server.

private static renameFile(FTPClient ftpClient, String oldName, String newName) throws IOException {
boolean success = ftpClient.rename(oldName, newName);
if (success) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename file.");
}
}

Delete the file from the FTP server.

private static void deleteFile(FTPClient ftpClient, String filePath) throws IOException {
boolean success = ftpClient.deleteFile(filePath);

if (success) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete file.");
}
}

Resume files from the FTP server.

 private void resume(FTPClient ftpClient, String remoteFilePath, String localFilePath) throws IOException {
// Check if the server supports resume
if (FTPReply.isPositiveIntermediate(ftpClient.getReplyCode())) {
// Set the restart offset to the size of the partially downloaded file
long restartOffset = getLocalFileSize("downloaded-file.txt");
ftpClient.setRestartOffset(restartOffset);
}

FileOutputStream localFile = new FileOutputStream(localFilePath, true); // Set append mode to true
boolean success = ftpClient.retrieveFile(remoteFilePath, localFile);
localFile.close();

if (success) {
System.out.println("File downloaded successfully.");
} else {
System.out.println("Failed to download file.");
}
}

private static long getLocalFileSize(String filePath) {
File file = new File(filePath);
return file.exists() ? file.length() : 0;
}

SFTP server connection.

The developer can use jsch library to connect the SFTP server.

Add maven dependency.

<!-- https://mvnrepository.com/artifact/com.github.mwiede/jsch -->
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>0.2.19</version>
</dependency>

Connect SFTP server.

import com.jcraft.jsch.*;
import java.io.File;
import java.util.Vector;

private static ChannelSftp setupJsch() throws JSchException {
String server = "127.0.0.1";
int port = 22;
String user = "nithidl.v";
String pass = "pass";
JSch jsch = new JSch();
jsch.setKnownHosts("../.ssh/known_hosts");
Session jschSession = jsch.getSession(user, server, port);
jschSession.setPassword(pass);
System.out.println("#connect begin.");
jschSession.connect();
System.out.println("#connect end.");
return (ChannelSftp) jschSession.openChannel("sftp");
}

List files from the FTP server.

private void list() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String remoteFile = "/path/folder/";
Vector<ChannelSftp.LsEntry> list = channelSftp.ls(remoteFile);
for (ChannelSftp.LsEntry entry : list) {
list.forEach((l)->System.out.println("FileNameOrFolderName="+l.getFilename()));
}
channelSftp.exit();
System.exit(0);
}

Download files from the server.

private void download() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String serverPath = "/path/folder/demo.txt";
String localPath = "c:/demo.txt";
channelSftp.get(serverPath, localPath);
channelSftp.exit();
System.exit(0);
}

Upload files from the server.

private void upload() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String serverPath = "/path/folder/demo.txt";
String localPath = "c:/demo.txt";
channelSftp.put(localPath, serverPath);
channelSftp.exit();
System.exit(0);
}

Delete files from the server.

private void delete() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String serverPath = "/path/folder/demo.txt";
channelSftp.rm(serverPath);
channelSftp.exit();
System.exit(0);
}

Rename files from the server.

private void rename() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String oldFilePath = "/path/folder/file.txt";
String newFilePath = "/path/folder/file2.txt";
channelSftp.rename(oldFilePath, newFilePath);
channelSftp.exit();
System.exit(0);
}

Finally, FTP is an easy way to transfer large files between the application server and storage or client and storage through the internet. Still, The developer must follow the security rules.

Thanks for reading.

If you enjoyed this article, please consider giving it a clap.

I would appreciate hearing your thoughts in the comments below!

Don’t miss out — follow me to stay connected and keep learning with me!

--

--

Nithidol Vacharotayan

Programming enthusiast with 10+ years of experience in Java loves sharing knowledge with others and exploring new technologies together!