Search code examples
javaftpapache-commons-net

When downloading a listed file using Apache Common Net FTPClient the downloaded file is empty or the returned InputStream is null


I am using Apache Commons Net FTP library for my FTP client project. I was successfully logged in, but got empty file or null InputStream, when I tried to download the file from FTP server.

I tried to set the file transfer mode or file type, but none of them works.

Here is my code example to initiate a client:

FTPClient client = new FTPClient();
client.connect(host, port);
client.login(user, password);

And this is code to retrieve the file:

// I do some filtering here, only download file containing certain prefix/suffix/text
FTPFile[] file = client.listFiles(fullDirectory, (file) -> file != null && file.isFile() && file.getName().contains(fileName));
// get the real file
// this will produce file with empty content
client.retrieveFile(file.getName(), new FileOutputStream(new File(file.getName))); 

// get InputStream
// this will produce null InputStream
InputStream is = client.retrieveFileStream(file.getName()); 

I've tried also to add some additional properties like:

FTPClient client = new FTPClient();
client.connect(host, port);
client.setFileType(FTP.ASCII_FILE_TYPE);
client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
client.login(user, password);

But none of them works.

Could this has to do with the server configuration or something? Actually I don't have configuration access to the FTP Server. The provider only gave me read access to it.


Solution

  • You are listing a specific directory (fullDirectory). But then you are downloading the file, you find, from the current working directory (without specifying the full path). So it probably cannot be found.

    Try combining the directory path with the file name:

    fullDirectory + "/" + file.getName()
    

    You are probably looking for this:
    Download entire FTP directory in Java (Apache Net Commons)