java - 如何正确关闭FTPClient FileStream

标签 java ftp apache-commons-net

我正在使用 Apache Commons Net 的 FTPClient 从位于服务器上的文件中读取内容。仅读取一次时效果很好。但是当我尝试读取第二个文件时,FTPClient 的 InputStream 返回 null。这是我的代码:

            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();

我做错了什么?

最佳答案

关闭InputStream后,执行以下操作:

ftpClient.completePendingCommand();

您可以在 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.

关于java - 如何正确关闭FTPClient FileStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040594/

相关文章:

java - 为什么通过 FTP 对包含 170K 文件的文件夹抛出 FTPConnectionClosedException?

java - 是否可以阻止一次触发 Action 监听器?

java - 找不到 org.junit.contrib 包

python - 如何使用 PIL 将图像保存在内存中并上传?

batch-file - 如何从命令行将用户名传递给 FTP 命令?

java - Apache SMTPClient 与 gmail 的连接时间

java - Android Studio 上构建 Java 版本错误

java - Android加密数据库

ios - 用指针转换 CFDictionaryRef?

java - 如何处理Camel FTP的 "Host attempting data connection x.x.x.x is not the same as server y.y.y.y"错误?