记Java使用ftp下载文件失败的坑

使用的jar包

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.6</version>
    </dependency>

背景:需要从ftp服务器上拿到指定目录下的多个文件

boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
     if (success) {
    	 log.info("File downloaded successfully.");
     } else {
         log.info("Failed to download file.");
     }

坑:下载单个文件没问题,下载多个文件会报错 百思不得其解

原因:
官方说法是:完成文件传输必须调用completependingcommand和检查它的返回值来验证成功。如果没有这样做,后续命令可能会意外地出错
简单来说:completePendingCommand()会一直在等FTP Server返回226 Transfer complete,但是FTP Server只有在接受到InputStream执行close方法时,才会返回。所以先要执行close方法
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/u012894692/article/details/79796160
解决方案:在使用public InputStream retrieveFileStream(String remote)

InputStream in = ftpClient.retrieveFileStream(fileName);
in.close();
ftpClient.completePendingCommand();

文章来自:https://blog.csdn.net/u012894692/article/details/79796160

posted @ 2024-08-21 16:41  Only_Aptx-4869  阅读(270)  评论(0)    收藏  举报