简体   繁体   English

恢复Java FTP文件下载

[英]Resume a Java FTP file download

I'm developing, in Java, an application that has to download from a server to client some very large files. 我正在用Java开发一个必须从服务器下载到客户端的非常大的文件的应用程序。 So far I'm using the apache commons-net: 到目前为止,我正在使用apache commons-net:

FileOutputStream out = new FileOutputStream(file);
client.retrieveFile(filename, out);

The connection commonly fails before the client finishes downloading the file. 客户端完成下载文件之前,连接通常会失败。 I need a way to resume the download of the file from the point where the connection failed, without downloading the whole file again, is it possible? 我需要一种方法来从连接失败的点恢复下载文件,而不必再次下载整个文件,这可能吗?

Things to know: 要知道的事情:

FileOutputStream has an append parameter, from doc; FileOutputStream具有来自doc的append参数;

@param append if true , then bytes will be written to the end of the file rather than the beginning @param append如果为true ,则字节将被写入文件的末尾而不是开头

FileClient has setRestartOffset which takes offset as parameter, from doc; FileClient具有setRestartOffset,它以doc作为偏移量作为参数;

@param offset The offset into the remote file at which to start the next file transfer. @param offset到远程文件的偏移量,从该偏移量开始下一个文件传输。 This must be a value greater than or equal to zero. 该值必须大于或等于零。

We need to combine these two; 我们需要将两者结合起来。

boolean downloadFile(String remoteFilePath, String localFilePath) {
  try {
    File localFile = new File(localFilePath);
    if (localFile.exists()) {
      // If file exist set append=true, set ofset localFile size and resume
      OutputStream fos = new FileOutputStream(localFile, true);
      ftp.setRestartOffset(localFile.length());
      ftp.retrieveFile(remoteFilePath, fos);
    } else {
      // Create file with directories if necessary(safer) and start download
      localFile.getParentFile().mkdirs();
      localFile.createNewFile();
      val fos = new FileOutputStream(localFile);
      ftp.retrieveFile(remoteFilePath, fos);
    }
  } catch (Exception ex) {
    System.out.println("Could not download file " + ex.getMessage());
    return false;
  }
}

Commons-net FTPClient supports restarting transfers from a specific offset. Commons-net FTPClient支持从特定偏移量重新开始传输。 You'll have to keep track of what you've successfully retrieved, send the correct offset, and manage appending to the existing file. 您必须跟踪已成功检索的内容,发送正确的偏移量,并管理附加到现有文件上。 Assuming, of course, that the FTP server you're connecting to supports the REST (restart) command. 当然,假设您要连接的FTP服务器支持REST (重新启动)命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM