I am using org.apache.commons.net.ftp.FTPClient
in one of my applications to work with a FTP server. I am able to connect
, login
, pwd
and cwd
. However, when I try to list
the files it doesn't return the list of files in that directory, where I know for sure that there are files. I am using the method FTPFile[] listFiles()
, it returns an empty array of FTPFile
.
Please find below the code snippet where I am trying this:
String hostname = properties.getProperty("FTP_SERVER");
String user = properties.getProperty("FTP_USER");
String passwd = properties.getProperty("FTP_PASSWD");
FTPClient client = new FTPClient();
client.connect(hostname);
client.login(user, passwd);
String reply = client.getStatus();
System.out.println(reply);
client.enterRemotePassiveMode();
client.changeWorkingDirectory("/uploads");
FTPFile[] files = client.listFiles();
System.out.println(files.length);
for (FTPFile file : files) {
System.out.println(file.getName());
}
String[] fileNames = client.listNames();
if (fileNames != null) {
for (String file : fileNames) {
System.out.println(file);
}
}
client.disconnect();
FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface.
Here's the official Apache download site for Commons Net. Once you've picked and extracted the appropriate version, set a dependency in your Eclipse project: Right-click the project and choose "Properties" Choose "Java Build Path" from the resulting popup.
Apache FTPClient doesn't support SFTP at the moment.
To start using FTP with Java, you will need to create a new FTPClient and then connect and login to the server using . connect(String server, int port) and . login(String username, String password) .
This seems like the same issue I had (and solved), see this answer:
Apache Commons Net FTPClient and listFiles()
After I set the mode as PASV
it is working fine now!
Thanks for all your efforts and suggestions!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With