gpt4 book ai didi

Java FTP 下载进度

转载 作者:行者123 更新时间:2023-11-29 05:56:22 24 4
gpt4 key购买 nike

我看了很多例子并试图理解我做错了什么但没有成功,也许你可以帮助我。它总是停在第二个文件处,但第一个文件只是装箱在 c:\上,大小为 0kb。files_server.get(i) 是包含我希望下载的所有文件的 ArrayList。

我的代码:

public FTPConnection() {

StartD std = new StartD();
std.start();
}

class StartD extends Thread{

@Override
public void run()
{
for (int i = 0; i < files_server.size(); i++) {
err = ftpDownload(files_server.get(i), "C:/"+ files_server.get(i));
if (!err)
{
System.out.println("Error in download, breaking");
break;
}
}
}

public boolean ftpDownload(String srcFilePath, String desFilePath)
{
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);
InputStream input = mFTPClient.retrieveFileStream(srcFilePath);
byte[] data = new byte[1024];
int count;
while ((count = input.read(data)) != -1)
{
desFileStream.write(data, 0, count);
}
desFileStream.close();

} catch (Exception e) {

return false;
}
return true;

}}

如果我使用函数:

public boolean ftpDownload(String srcFilePath, String desFilePath) {
boolean status = false;
try {

FileOutputStream desFileStream = new FileOutputStream(desFilePath);
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {

}
return status;
}

相反,一切正常,但我无法监控文件下载进度。

最佳答案

我只将它用于文件解压缩而不是 FTP,但在那种情况下 InputStream 缓冲区可以返回零,所以我认为值得尝试将 while 循环更改为类似以下内容:

while ((count = input.read(data)) >= 0)

public int read(byte[] b) throws IOException

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of b is zero, then no bytes are read and 0 is returned;

也可能是您分配了两次计数,这可能会从数据中删除第一个字节:

int count  = input.read(data);
while ((count = input.read(data)) != -1)

所以当你声明它时不要分配任何东西来计数。

关于Java FTP 下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11965719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com