【问题标题】:Resume a Java FTP file download恢复 Java FTP 文件下载
【发布时间】:2013-07-25 21:59:56
【问题描述】:

我正在用 Java 开发一个应用程序,该应用程序必须从服务器下载一些非常大的文件到客户端。到目前为止,我使用的是 apache commons-net:

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

连接通常在客户端完成下载文件之前失败。我需要一种方法来从连接失败的位置恢复文件的下载,而无需再次下载整个文件,这可能吗?

【问题讨论】:

  • @LeeMeador 不正确,许多 FTP 服务器支持从特定字节偏移量恢复。如果 commons-net 不支持发送起始偏移量,我会感到惊讶。

标签: java ftp apache-commons-net


【解决方案1】:

须知:

FileOutputStream 有一个附加参数,来自 doc;

@param 追加如果true,那么字节将被写入 到文件末尾而不是开头

FileClient 有 setRestartOffset,它以偏移量为参数,来自 doc;

@param offset 远程文件开始的偏移量 下一次文件传输。这必须是一个大于或 等于零。

我们需要将这两者结合起来;

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;
  }
}

【讨论】:

    【解决方案2】:

    Commons-net FTPClient 支持从特定偏移量重新开始传输。您必须跟踪已成功检索的内容、发送正确的偏移量并管理附加到现有文件。当然,假设您要连接的 FTP 服务器支持 REST(重新启动)命令。

    【讨论】:

    • 你能给我举个例子吗?到目前为止,我正在研究 FTP Client 类,但是有太多东西我不太确定最好使用什么。
    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多