2

I'm developing, in Java, an application that has to download from a server to client some very large files. So far I'm using the 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?

4

2 回答 2

5

要知道的事情:

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

@param append if 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;
  }
}
于 2015-12-09T21:23:55.253 回答
2

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

于 2013-07-25T22:06:07.257 回答