继续下载Java FTP文件
我正在用Java开发一个应用程序,它必须从服务器下载一些非常大的文件到客户端。到目前为止,我使用的是apache commons网络:继续下载Java FTP文件,java,ftp,apache-commons-net,Java,Ftp,Apache Commons Net,我正在用Java开发一个应用程序,它必须从服务器下载一些非常大的文件到客户端。到目前为止,我使用的是apache commons网络: FileOutputStream out = new FileOutputStream(file); client.retrieveFile(filename, out); 在客户端完成下载文件之前,连接通常会失败。我需要一种方法,从连接失败的点恢复文件下载,而不重新下载整个文件,是否可行?Commons netFTPClient支持从特定偏移重新启动传输。您
FileOutputStream out = new FileOutputStream(file);
client.retrieveFile(filename, out);
在客户端完成下载文件之前,连接通常会失败。我需要一种方法,从连接失败的点恢复文件下载,而不重新下载整个文件,是否可行?Commons net
FTPClient
支持从特定偏移重新启动传输。您必须跟踪已成功检索的内容,发送正确的偏移量,并管理附加到现有文件。当然,假设您连接的FTP服务器支持REST(重新启动)命令。需要了解的事项:
FileOutputStream有一个append参数,from doc
@param append如果true
,则将写入字节
到文件的结尾而不是开始
FileClient具有setRestartOffset,以偏移量为参数,来自单据
@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;
}
}
@LeeMeador不正确,许多FTP服务器支持从特定字节偏移量恢复。如果commons net不支持发送起始偏移量,我会感到惊讶。你能给我举个例子吗?到目前为止,我正在研究FTP客户机类,但有太多的东西,我不太确定什么是最好的使用。