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

问题描述 投票:0回答:3

我有需要从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连接?

java ftp ftp-client apache-commons-net
3个回答
1
投票

根据documentation of the FTPClient.retrieveFileStream() method

当您完成对InputStream的读取后,必须关闭它。 InputStream本身将在关闭后关闭父数据连接套接字。

关闭流时,您的客户端连接也会关闭。因此,您无需一遍又一遍地使用同一客户端,而需要为每个文件创建一个新的客户端连接。


0
投票
  1. 我没有看到输出流没有正确关闭。

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.