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>
<!-- https://search.maven.org/remotecontent?filepath=commons-net/commons-net/3.8.0/commons-net-3.8.0-examples.jar -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=commons-io/commons-io/2.11.0/commons-io-2.11.0.jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
Thanks! The code’s working 🙂