Search code examples
javaandroidftpapache-commons-net

Apache Commons FTP storeFileStream returns null


I am trying to upload a file in android to an FTP server using the apache.commons.ftp library.

Note: I am using storeFileStream so that I can track the progress of the upload.

ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = new FileInputStream(localFile);
OutputStream outputStream = ftpClient.storeFileStream(remoteFile);
byte[] buffer = new byte[8192];
int bytesRead;
logMessage("Starting to upload file");

while ((bytesRead = inputStream.read(buffer)) != -1) {
    total += bytesRead;
    outputStream.write(buffer, 0, bytesRead); //output stream is null here
    latestPercentDone = (int) ((total / (float) totalMegaBytes) * 100);
    if (percentDone != latestPercentDone) {
        percentDone = latestPercentDone;
        publishProgress(""+percentDone);
    }
}
inputStream.close();
outputStream.close();
ftpClient.completePendingCommand();

I am using the speedtest.tele2.net server for testing. Using an anonymous login.

The log keeps saying the outputstream is null.

EDIT: Using what Martin Prikryl and getting the error code, i found the problem to be the location of the remote file.

Upload to a location rather than a directory.

For example if the file is caled item1.txt the remote file should be /item1.txt or /someFolder/AnotherFolder/item1.txt rather than /someFolder/AnotherFolder/


Solution

  • The FTPClient.storeFileStream method can return null:

    An OutputStream through which the remote file can be written. If the data connection cannot be opened (e.g., the file does not exist), null is returned (in which case you may check the reply code to determine the exact reason for failure).

    Though the "file does not exist" note is nonsense for upload, it's obviously a copy-and-paste error from the .retrieveFileStream (download).


    Use the .getReplyCode and .getReplyString, to see what went wrong.