Fayre
Fayre

Reputation: 83

How to close FTPClient FileStream properly

I'm reading the content from a file located on a server with the FTPClient from Apache Commons Net. It works fine when only reading once. But when I'm trying to read a second file, the InputStream of my FTPClient returns null. This is my code:

            FTPClient ftpClient = new FTPClient();
            ftpClient.connect("myhostname");
            ftpClient.login("myusername", "mypassword");

            // read InputStream from file
            InputStream inputStream = ftpClient.retrieveFileStream("/my/firstfile.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            // read every line...

            // close everything
            inputStream.close();
            bufferedReader.close();


            // second try
            inputStream = ftpClient.retrieveFileStream("/my/secondfile.txt");
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            // ...
            inputStream.close();
            bufferedReader.close();

What am I doing wrong?

Upvotes: 0

Views: 2039

Answers (1)

Duarte Meneses
Duarte Meneses

Reputation: 2938

After closing the InputStream, do the following:

ftpClient.completePendingCommand();

You can find more information in the javadoc of FTPClient#retrieveFileStream:

To finalize the file transfer you must call completePendingCommand and check its return value to verify success. If this is not done, subsequent commands may behave unexpectedly.

Upvotes: 4

Related Questions