ftp下载方法-师兄的创作

ftp下载方法

public int downloadFtpFiles(String ftpAddr,String ftpUser,String ftpPass,String localPath,String fileTimestamp,String logFileName, boolean overwrite) throws ServiceException {
		if(StringUtils.isEmpty(ftpAddr)) {
			logger.warn("no ftp server!");
			return 0;
		}
		
		if(!ftpAddr.endsWith("/") && !ftpAddr.endsWith("\\")) 
			ftpAddr += "/";
		
		int fileNum=0;
		FTPClient ftpClient = new FTPClient();
		ftpClient.addListParser(new Window2003ListParser());
		String remotePath = ftpAddr+fileTimestamp+"/";
		try {
			URL url = new URL(remotePath);
			
			if("ftp".equalsIgnoreCase(url.getProtocol())) {
				
				logger.debug("connecting ftp server "+ftpAddr+" ...");
				ftpClient.connect(url.getHost(), url.getPort()>0?url.getPort():21);
				
				logger.debug("login to ftp server ...");
				ftpClient.login(ftpUser, ftpPass);
				
				logger.debug("change to "+url.getPath()+" ...");
				try {
					ftpClient.changeDirectory(url.getPath());
				} catch (Exception e) {
					//e.printStackTrace();
					logger.error(e,e.fillInStackTrace()); // 可能目录不存在
					return 0;
				}
				
				// 遍历并下载文件 
				logger.debug("list files ");
				
				FTPFile[] ftpFiles = ftpClient.list(); // 缺省按字典顺序排序
				for (int i = 0; i < ftpFiles.length; i++) {
					FTPFile ftpFile = ftpFiles[i];
					if (ftpFile==null || ftpFile.getType()!=FTPFile.TYPE_FILE) continue;
					logger.debug("downloading file "+ftpFile.getName()+"...");
					ftpClient.setType(FTPClient.TYPE_BINARY); // TYPE_AUTO TYPE_TEXTUAL TYPE_BINARY
					File localFile = new File(localPath+fileTimestamp+"/"+ftpFile.getName());
					if(overwrite || !localFile.exists()){
						ftpClient.download(ftpFile.getName(), localFile);
						if(cicapFileLogExport!=null){
				    		cicapFileLogExport.save("下载"+remotePath+ftpFile.getName(), logFileName);
						}
						fileNum++;
					}
				}
			}
			logger.debug("下载文件数:"+fileNum);
			
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error(e,e.fillInStackTrace());
			throw new ServiceException("下载FTP服务器文件失败!",null,e);
		}finally{
			try {
				ftpClient.disconnect(true);
			} catch (Exception ex) {
				logger.error(ex.getMessage());
			}
		}
		
		return fileNum;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值