恢复 Java FTP 文件下载

Pie*_*vis 2 java ftp apache-commons-net

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

FileOutputStream out = new FileOutputStream(file);
client.retrieveFile(filename, out);
Run Code Online (Sandbox Code Playgroud)

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

end*_*unc 5

须知:

FileOutputStream 有一个 append 参数,来自 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;
  }
}
Run Code Online (Sandbox Code Playgroud)