java - 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件

标签 java ftp ftp-client apache-commons-net

我有需要从 FTP 服务器读取的文件列表。 我有一个方法 readFile(String path, FTPClient client) 可以读取并打印文件。

public byte[] readFile(String path,FTPClient client){
    InputStream inStream = null;
    ByteArrayOutputStream os = null;
    byte[] finalBytes = new byte[0];
            int reply;
    int len;
    byte[] buffer = new byte[1024];
    try{
        os = new ByteArrayOutputStream();
        inStream = client.retrieveFileStream(path);
        reply = client.getReplyCode();
        log.warn("In getFTPfilebytes() :: Reply code -"+reply);

        while ((len = inStream.read(buffer)) != -1) {
                    // write bytes from the buffer into output stream
                    os.write(buffer, 0, len);
                }
        finalBytes = os.toByteArray();

    if(inStream == null){
        throw new Exception("File not found");
    }

    inStream.close();
    }catch(Exception e){

    }finally{
        try{ inStream.close();} catch(Exception e){}
    }
    return finalBytes;

}

我在包含文件路径字符串的列表循环中调用上述方法。

问题 - 在循环中只有第一个文件被正确读取。之后,它不会读取文件并引发异常。 inStream 为第二次迭代/第二个文件提供 NULL。此外,在 retrieveFileStream 之后迭代第一个文件回复代码时,“125(数据连接已打开;传输开始。)

在第二次迭代中,它给出“200(请求的操作已成功完成。)”

我无法理解这里出了什么问题。 没有正确关闭 inputstream 连接吗?

最佳答案

您必须调用FTPClient.completePendingCommand并关闭输入流,如 FTPClient.retrieveFileStream 的文档说:

Returns an InputStream from which a named file from the server can be read. If the current file type is ASCII, the returned InputStream will convert line separators in the file to the local representation. You must close the InputStream when you finish reading from it. The InputStream itself will take care of closing the parent data connection socket upon being closed.

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.

<小时/>
inStream = client.retrieveFileStream(path);
try {
    while ((len = inStream.read(buffer)) != -1) {
        // write bytes from the buffer into output stream
        os.write(buffer, 0, len);
    }
    finalBytes = os.toByteArray();
} finally {
    inStream.close()
    if (!client.completePendingCommand()) {
        // error
    }
}
<小时/>

顺便说一句,有更好的方法从 InputStream 复制到 OutputStream:
Easy way to write contents of a Java InputStream to an OutputStream

关于java - 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167086/

相关文章:

java - IP 地址上的 UnknownHostException

java - FTP 上传错误 "553 Could not create file"

ftp - Telnet 和被动 FTP

java - 使用 commons.net FTPClient 下载后 Tar.gz 损坏

java - 如何动态实例化引用其他类的类

java - 如何用Java语言计算整数m使得m^3 <= Long.MAX_VALUE < (m + 1)^3?

java - 如何为前端Web应用程序编写dockerfile

java - Perl 与 Java 中的多线程

java - 将 csv 文件上传到 ftp,无需在本地创建物理文件

linux - 使用ftp上传文件夹中的所有文件