I am using Apache Commons net FTPClient to login and read files from an FTP Server. I manage to login and I can see it logs in successfully, because it shows the working directory path in the header string. However it shows no files when I use listFiles()
. (I have also tried using listDirectories()
and listNames()
but with no success)
Below is a snippet:
try {
client.connect(ftpHost);
} /*catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/ catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
String header ="";
InputStream stream=null;
BufferedReader reader=null;
try{
client.login(ftpUser, ftpPass);
client.changeWorkingDirectory(targetWorkingDir);
header = client.printWorkingDirectory();
//client.setFileType(FTP.BINARY_FILE_TYPE);
for(int i=0; i<client.listFiles().length;i++){
header+=client.listFiles()[i].getName() +"\n";
}
}
catch (IOException ex){
ex.printStackTrace();
header="ERROR 1: " + ex.getMessage();
for(int i=0;i<ex.getStackTrace().length;i++){
header += "\n" + ex.getStackTrace()[i];
}
}
catch(NullPointerException e){
header = "ERROR 2: "+ e.getMessage()+"\n";
for(int i=0;i<e.getStackTrace().length;i++){
header+= e.getStackTrace()[i] + "\n";
}
}
finally{
if(reader!=null){
try{reader.close();}catch(IOException e){e.printStackTrace();}
try{stream.close();}catch(IOException e){e.printStackTrace();}
}
}
I have also tried using something like this to read a file:
try {
stream = ftpClient.retrieveFileStream("klasa.csv");
reader = new BufferedReader(new InputStreamReader(stream));
header = reader.readLine();
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore){}
}
In both cases I'm pretty sure I'm at the right directory, and I make sure that my file is there via FileZilla, but the client can't seem to read any file.
Try to avoid calling listFiles() in the loop. Every call will perform the entire FTP LIST command sequence, so eventually, you will add unnecessary traffic to every call.
You can try to simplify your program first like this:
If this program will not give you the list of files in the root directory of your server, you can try to compare your FileZilla FTP options (PASSIVE/ACTIVE mode in particular): https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#enterLocalPassiveMode()
If it won't help you can try to sniff the network traffic using WireShark or tcpdump and compare the commands set to the FTP server.