This example demonstrates how to retrieve a 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 is 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.10.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024
Thanks! The code’s working 🙂