ftpClient读取文件流的偶尔会是空文件

 

遇到问题:

 1.下载文件时候, InputStream  为null,在  ftpClient.retrieveFileStream 之前加上 ftpClient.enterLocalPassiveMode();

 然后可以下载文件了,但是在下载文件的过程中遇到了 偶尔会有文件下载后打开为空的情况,十次下载总会有两三次这样的情况,排查了很久不知原因。

2.最后发现  in.available() 为0,进不了while循环,os中为空。

就在ftpClient.retrieveFileStream   之后加上了  Thread.sleep(1000);   给ftpclient一点读取时间,测试十多遍都会有数据。

猜测ftpClient.retrieveFileStream 读取文档的过程偶尔会很慢。

以上是自己使用过程中的经验,有问题欢迎高手指出。

 

 

 

好的,以下是使用Apache Commons Net库中的FTPClient读取单个文件的步骤: 1. 创建FTPClient对象并连接到FTP服务器: ```java FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); ``` 2. 设置FTPClient以二进制模式传输文件: ```java ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ``` 3. 切换到需要读取文件的目录: ```java ftpClient.changeWorkingDirectory(remoteFilePath); ``` 4. 使用retrieveFile()方法读取文件: ```java OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); ftpClient.retrieveFile(fileName, outputStream); outputStream.close(); ``` 其中,remoteFilePath是FTP服务器上文件所在的路径,fileName是需要读取文件名,localFile是本地存储文件的路径和文件名。 5. 断开FTP连接: ```java ftpClient.logout(); ftpClient.disconnect(); ``` 完整的代码示例: ```java import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; public class FTPClientDemo { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String username = "username"; String password = "password"; String remoteFilePath = "/remote/folder"; String fileName = "example.txt"; String localFilePath = "C:/local/folder/example.txt"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(remoteFilePath); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFilePath)); ftpClient.retrieveFile(fileName, outputStream); outputStream.close(); ftpClient.logout(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } catch (Exception ex) { ex.printStackTrace(); } } } } ``` 希望这可以帮助到您!
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值