Android FTPClient – retrieveFileStream() always returns null

androidapache-commons-netftp-client

I am a newbie to Android. I am trying download a file from ftp server to sdcard using Apache Commons FTPClient. The line InputStream input = client.retrieveFileStream("/" + fileName); always returns null. But the file is there in Ftp location. Kindly help me to know where the mistake is.

I have set the following permissions in my manifest; android:name="android.permission.INTERNET" and android:name="android.permission.WRITE_EXTERNAL_STORAGE"

My Code

private static void downLoad(){
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;

    try {
        client.connect("ftp.doamin.com");
        client.login("8888", "8888");
String filePath = "/mnt/sdcard/download/CheckboxHTML.txt" ;
String fileName = "CheckboxHTML.txt";
fos = new FileOutputStream(filePath);
InputStream input = client.retrieveFileStream("/" + fileName);
byte[] data = new byte[1024];
int count  = input.read(data); 
while ((count = input.read(data)) != -1) {
      fos.write(data, 0, count);
}
fos.close();
      if(!client.completePendingCommand()) { 
      client.logout(); 
      client.disconnect(); 
      System.err.println("File transfer failed."); 
} 
    } catch (SocketException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
    }

}

Thanks for your time and interest. Ananth.

Best Answer

AFAIK. You are suppose to finalize file transfers by calling completePendingCommand() and verifying that the transfer was indeed successful. i.e. you need to add call the function below fos.clos().

fos.close();
client.completePendingCommand()

You may also consider this, according to the API for FTPClient.retrieveFileStream(), the method returns null when it cannot open the data connection, in which case you should check the reply code (e.g. getReplyCode(), getReplyString(), getReplyStrings()) to see why it failed.