Java FTP 下载进度

标签 java ftp download

我看了很多例子并试图理解我做错了什么但没有成功,也许你可以帮助我。它总是停在第二个文件处,但第一个文件只是装箱在 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/

相关文章:

java - 使用 JodaTime 添加月份?

java - 获取字符数组的子数组

C++ ftp上传错误

c# - 是否可以使用 C# 对 FTP 中的文件夹进行 ZIP 压缩?

python - 如何使用请求模块从网络下载文件?

PHP如何限制并行下载?

java - 如何删除动态添加的 TextView

javascript - java中等效的node.js Buffer是什么?

c++ - 如何在不保存文件的情况下制作打印屏幕并将其发送到 FTP 服务器?我的工作代码将文件保存到 HDD

ios - iOS 上的 CocoaHTTPServer : set up server so user can download NSData as file