80,351
社区成员
发帖
与我相关
我的任务
分享
/**
* 下载单个文件,可实现断点下载.
*
* @param serverPath
* Ftp目录及文件路径
* @param localPath
* 本地目录
* @param fileName
* 下载之后的文件名称
* @param listener
* 监听器
* @throws IOException
*/
public boolean downloadSingleFile(String serverPath, String localPath, String fileName)
throws Exception {
// 判断FTP是否仍在连接
if (!ftpClient.isConnected()) {
if (!initFTPSetting(FTPUrl, FTPPort, UserName, UserPassword)) {
return false;
}
}
// 先判断服务器文件是否存在
FTPFile[] files = ftpClient.listFiles(serverPath);
if (files.length == 0) {
// listener.onDownLoadProgress(MainActivity.FTP_FILE_NOTEXISTS, 0, null);
return false;
}
//创建本地文件夹
File mkFile = new File(localPath);
if (!mkFile.exists()) {
mkFile.mkdirs();
}
localPath = localPath + fileName;
// 接着判断下载的文件是否能断点下载
long serverSize = files[0].getSize(); // 获取远程文件的长度
File localFile = new File(localPath);
long localSize = 0;
if (localFile.exists()) {
localSize = localFile.length(); // 如果本地文件存在,获取本地文件的长度
if (localSize >= serverSize) {
File file = new File(localPath);
file.delete();
}
}
// 进度
long step = serverSize / 100;
long process = 0;
long currentSize = 0;
// 开始准备下载文件
OutputStream out = new FileOutputStream(localFile, true);
ftpClient.setRestartOffset(localSize);
InputStream input = ftpClient.retrieveFileStream(serverPath);
byte[] b = new byte[1024];
int length = 0;
while ((length = input.read(b)) != -1) {
out.write(b, 0, length);
currentSize = currentSize + length;
if (currentSize / step != process) {
process = currentSize / step;
// if (process % 5 == 0) { //每隔%5的进度返回一次
// listener.onDownLoadProgress(MainActivity.FTP_DOWN_LOADING, process, null);
// }
}
}
out.flush();
out.close();
input.close();
// 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉
if (ftpClient.completePendingCommand()) {
// listener.onDownLoadProgress(MainActivity.FTP_DOWN_SUCCESS, 0, new File(localPath));
} else {
// listener.onDownLoadProgress(MainActivity.FTP_DOWN_FAIL, 0, null);
}
// 下载完成之后关闭连接
this.closeConnect();
// listener.onDownLoadProgress(MainActivity.FTP_DISCONNECT_SUCCESS, 0, null);
return true;
}
/**
* 关闭FTP服务.
*
* @throws IOException
*/
public void closeConnect() throws IOException {
if (ftpClient != null) {
// 退出FTP
ftpClient.logout();
// 断开连接
ftpClient.disconnect();
}
}