0

I have a list of FTP files and I can only convert the first FTPFile to File. I am using org.apache.commons.net.ftp library.
My code is works fine for the first time:

for (FTPFile file : files) {
  if(ftpClient.sendNoOp()){
   if(file.getName()!=null || !file.getName().equals("")) {
           InputStream iStream=ftpClient.retrieveFileStream(file.getName());
           File file2 = File.createTempFile("xml", null);
           FileUtils.copyInputStreamToFile(iStream, file2);
           iStream.close();
                }
  }
}

From this code the loop traverse only time and the FTPFile is converted to File and after that it will get exception which is created by null value generated in ftpClient.retrieveFileStream(file.getName()).
Please help.

Paul Cheriyan
  • 638
  • 9
  • 19
  • Take a look on what FTPFile.getName() returns. I suspect it returns the file name only and not the whole file path that, I assume, retrieveFileStream is expecting for. – VeryNiceArgumentException Feb 28 '18 at 07:52
  • It should be a name, there are no local files except the temp file. However, as far as I can see you are not closing the input stream? Perhaps you need to complete the first file transfer before you start a new one? Add a try-with-resources block and see if that helps. – ewramner Feb 28 '18 at 08:00
  • FTPFile.getName() Gets the file name in evey loop ..and was working fine for the first loop or first file @rlm – Paul Cheriyan Feb 28 '18 at 08:25
  • @user2612030 I have closed the input stream and still geting the same error – Paul Cheriyan Feb 28 '18 at 08:43
  • Please catch the exception and write the file name for the failed file. It may be that you are trying to fetch a directory or some kind of special file that can't be read. – ewramner Feb 28 '18 at 08:54

2 Answers2

1

You will have to finalize the transfer after you download the file. That is the reason you are able to download your first file and having issue with the download of second file.

 success = ftpClient.completePendingCommand();
 if (success) {
                System.out.println("File has been downloaded successfully.");
  }

If still issue persists, you can invoke ftpClient.getReplyCode() which will let you know why you are not able to download the file. Generally retrieveFileStream returns null when it cannot open the data connection

CGS
  • 2,782
  • 18
  • 25
0

From the Javadoc for FTPClient#listFiles():

NOTE: This array may contain null members if any of the individual file listings failed to parse. The caller should check each entry for null before referencing it.

You must check for null on each and every item returned in the array, otherwise you will get NPEs.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190