This example demonstrate how to retrieve list of files from FTP server. First we create an instance of org.apache.commons.net.ftp.FTPClient
. Connect to the FTP server and login with your username and password.
The listFiles()
method of the FTPClient
return the list of filenames contained in the current working directory. null
if the list could not be obtained. If there are no filenames in the directory, a zero-length array is returned.
package org.kodejava.commons.net;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.IOException;
public class FTPListDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("ftp.example.com");
client.login("demo", "password");
if (client.isConnected()) {
// Obtain a list of filenames in the current working
// directory. When no file found an empty array will
// be returned.
String[] names = client.listNames();
for (String name : names) {
System.out.println("Name = " + name);
}
FTPFile[] ftpFiles = client.listFiles();
for (FTPFile ftpFile : ftpFiles) {
// Check if FTPFile is a regular file
if (ftpFile.getType() == FTPFile.FILE_TYPE) {
System.out.printf("FTPFile: %s; %s%n",
ftpFile.getName(),
FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
}
}
}
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is the example result of our code:
Name = example.html
Name = Touch.dat
FTPFile: examples.html; 1 bytes
FTPFile: Touch.dat; 0 bytes
Maven Dependencies
<dependencies>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thanks! The code’s working 🙂