14daf9d787ba4a1756d6c90e8ec04ea72badd848.svn-base 17.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
package com.thinkgem.jeesite.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.ftp.Ftputil;
 

/**
 * FTP 访问工具类
 * 
 * @author Administrator
 * 
 */
public class FTPUtil {

	private static Logger logger = LoggerFactory.getLogger(FTPUtil.class);

	private FTPClient ftpClient;
	private Boolean is_connected = false;
	private String defaultWorkSpace;

	/**
	 * FTP 初始化,
	 * 
	 * @param ip
	 *            FTP服务器地址
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP服务器登录用户名
	 * @param passwd
	 *            FTP服务器登录密码
	 * @param workSpace
	 *            FTP服务器默认存储路径
	 */
	public FTPUtil(String ip, int port, String username, String passwd,
			String workSpace) {
		ftpClient = new FTPClient();
		try {
			ftpClient.connect(ip, port);
			ftpClient.login(username, passwd);
			ftpClient.changeWorkingDirectory(workSpace);
			defaultWorkSpace = workSpace;
			is_connected = true;
			//setOutTime(Ftputil.IMAGE_FTP_DEFAULTTIMEOUT);
		} catch (SocketException e) {
			logger.error("FTP地址" + ip + ":" + port + "连接错误," + e.getMessage());
			e.printStackTrace();
			throw new ServiceException("FTP地址" + ip + ":" + port + "连接错误,"
					+ e.getMessage());
		} catch (IOException e) {
			logger.error("FTP地址" + ip + ":" + port + "连接登录错误," + e.getMessage());
			e.printStackTrace();
			throw new ServiceException("FTP地址" + ip + ":" + port + "连接登录错误,"
					+ e.getMessage());
		}
		logger.info("FTP地址" + ip + ":" + port + "连接成功");
	}

	/**
	 * 简历
	 * 
	 * @param ip
	 * @param port
	 * @param username
	 * @param passwd
	 * @param workSpace
	 */
	public void createconnect(String ip, int port, String username,
			String passwd, String workSpace) {
		if (is_connected) {
			cut_connnect();
		}
		ftpClient = new FTPClient();
		try {
			ftpClient.connect(ip, port);
			ftpClient.login(username, passwd);
			ftpClient.changeWorkingDirectory(workSpace);
			defaultWorkSpace = workSpace;
			is_connected = true;
			//setOutTime(Ftputil.IMAGE_FTP_DEFAULTTIMEOUT);
		} catch (SocketException e) {
			logger.error("FTP地址" + ip + ":" + port + "连接错误," + e.getMessage());
			e.printStackTrace();
			throw new ServiceException("FTP地址" + ip + ":" + port + "连接错误,"
					+ e.getMessage());
		} catch (IOException e) {
			logger.error("FTP地址" + ip + ":" + port + "连接登录错误," + e.getMessage());
			e.printStackTrace();
			throw new ServiceException("FTP地址" + ip + ":" + port + "连接登录错误,"
					+ e.getMessage());
		}
		logger.info("FTP地址" + ip + ":" + port + "连接成功");
	}

	/**
	 * 获取ftp文件夹中的所有文件信息 多层文件夹的文件路径以文件路径+文件名显示
	 * 
	 * @param remotePath
	 *            FTP 文件夹路径
	 * @return
	 * @throws IOException 
	 */
	public List getFilesNameByPath(String remotePath) throws IOException {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		/** 本地字符编码 */
		String LOCAL_CHARSET = "utf-8";
		ftpClient.enterLocalPassiveMode(); // 被动模式
		ftpClient.setCharset(Charset.forName("UTF-8"));
		if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
				"OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(utf-8).
				LOCAL_CHARSET = "UTF-8"; 
		}
		ftpClient.setControlEncoding(LOCAL_CHARSET);
		List files = new ArrayList();
		try {
			//Boolean ss = ftpClient.changeWorkingDirectory(remotePath);
			String path = new String(remotePath.getBytes("utf-8"),"iso-8859-1");
			logger.info("获取文件夹{}",remotePath);
			FTPFile[] filelist = ftpClient.listFiles(path);
			for (FTPFile file : filelist) {
				if (file.isDirectory()) {
					//String name = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
					files.addAll(getFilesNameByPath(remotePath + "/"+ file.getName()));
				} else {
					Map map = new HashMap();
					map.put("filename", file.getName());
					map.put("url", path);
					files.add(map);
					logger.info("获取文件  " + path + File.separator + file.getName()
							+ "成功");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return files;
	}

	/**
	 * 下载FTP文件夹中单个文件到本地文件夹中(建立传入远程文件夹(参数remotePath)所包含的路径)
	 * 
	 * @param remotePath
	 *            FTP文件夹路径
	 * @param localPath
	 *            本地文件夹的路径
	 * @param iscover
	 *             是否覆盖已存在的文件  true 覆盖
	 * @return
	 * @throws IOException
	 */
	public List downFileByPath(String remotePath, String localPath, String localFileName, Boolean iscover) {
		if (!this.is_connected) {
			logger.info("ftp 未连接或连接已断开,请初始化FTP工具类");
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		String fileurl =localPath;
//		if("\\".equals(File.separator)){
//			if(fileurl.indexOf("/")>=0){
//				fileurl = fileurl.replaceAll("/", "\\\\");
//			}
//		}else{
//			if(fileurl.indexOf("\\\\")>=0){
//				fileurl = fileurl.replaceAll("\\\\", File.separator);
//			}
//		}
		File newfile = new File(fileurl);
		logger.info("存在{} 地址{} 目录标志{}",newfile.exists(),fileurl,newfile.isDirectory());
		if(!newfile.exists()) { 
				boolean ss =newfile.mkdirs();
				logger.info("目录创建成功标志:"+ss);
			 
		}
		if (!newfile.isDirectory()) {
			newfile = new File(fileurl.substring(0,fileurl.lastIndexOf(File.separator)));
		}else {
			//
		}
		return downFiles(remotePath, newfile.getPath(), localFileName ,iscover);
		
	}
	
	
	public List downFiles(String remotePath, String localPath, String localFileName,Boolean iscover) {
		if (!this.is_connected) {
			logger.info("ftp 未连接或连接已断开,请初始化FTP工具类");
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		List fileList = new ArrayList();

		try { 
			/** 本地字符编码 */
			String LOCAL_CHARSET = "utf-8";
			ftpClient.enterLocalPassiveMode(); // 被动模式
			ftpClient.setCharset(Charset.forName("UTF-8"));
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
					"OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(utf-8).
					LOCAL_CHARSET = "UTF-8"; 
			}
			ftpClient.setControlEncoding(LOCAL_CHARSET); 
			String path = new String(remotePath.getBytes("utf-8"),"iso-8859-1");
			
			
			
//			if("\\".equals(File.separator)){
//				if(path.indexOf("/")>=0){
//					path = path.replaceAll("/", "\\\\");
//				}
//			}else{
//				if(path.indexOf("\\\\")>=0){
//					path = path.replaceAll("\\\\", File.separator);
//				}
//			}
			FTPFile[] files = ftpClient.listFiles(path);
			String remotename=path.substring(path.lastIndexOf("/")+1);
			
			for (FTPFile file : files) {
				if (file.isDirectory()) {
					File newfile = new File(localPath + File.separator + file.getName());
					newfile.mkdirs();
					fileList.addAll(downFilesByPath(
							path + File.separator + file.getName(), localPath + File.separator
									+ file.getName(),iscover));
				} else {
					if(StringUtils.isEmpty(localFileName)) {
						localFileName = file.getName();
					}
					File newfile = new File(localPath + File.separator + localFileName);
					if (newfile.exists()) {
						logger.info(localPath + File.separator + localFileName + "存在");
						//iscover  覆盖标记为false,执行下一次循环
						if(!iscover){
							continue;
						}
					}
					FileOutputStream out = new FileOutputStream(newfile);
					String ftpwj = "";
					if(remotename.equals(file.getName())){
						ftpClient.retrieveFile(path,out);
						ftpwj = path;
					}else{
						ftpClient.retrieveFile(path + File.separator + file.getName(),
								out);
						ftpwj=path + File.separator + file.getName();
					}
					
					out.flush();
					out.close();
					Map map = new HashMap();
					map.put("filename", file.getName());
					map.put("url", path);
					fileList.add(map);
					logger.info("成功下载文件  " + ftpwj);
				}
			}
		} catch (IOException e) {

		}
		return fileList;
	}
	
	/**
	 * 下载FTP文件夹中所有文件到本地文件夹中
	 * 
	 * @param remotePath
	 *            FTP文件夹路径
	 * @param localPath
	 *            本地文件夹的路径
	 * @param iscover
	 *             是否覆盖已存在的文件  true 覆盖
	 * @return
	 * @throws IOException
	 */
	public List downFilesByPath(String remotePath, String localPath,Boolean iscover) {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		List fileList = new ArrayList();
		File newdirectory = new File(localPath);
		if (!newdirectory.exists()) {
			newdirectory.mkdirs();
		}
		try {
			// 设置默认工作空间
			ftpClient.changeWorkingDirectory(defaultWorkSpace);
			ftpClient.enterLocalPassiveMode(); // 被动模式
			ftpClient.setCharset(Charset.forName("UTF-8"));

			FTPFile[] files = ftpClient.listFiles(remotePath);
			for (FTPFile file : files) {
				if (file.isDirectory()) {
					File newfile = new File(localPath + File.separator + file.getName());
					newfile.mkdirs();
					fileList.addAll(downFilesByPath(
							remotePath + File.separator + file.getName(), localPath + File.separator
									+ file.getName(),iscover));
				} else {
					File newfile = new File(localPath + File.separator + file.getName());
					   String fileName = newfile.getName();
					 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				        logger.info(suffix+"---");
					if("dmp".equalsIgnoreCase(suffix)){
						logger.warn(localPath + File.separator + file.getName() + "不下载");
							continue;
					}
				        
					if (newfile.exists()) {
						logger.warn(localPath + File.separator + file.getName() + "存在");
						//iscover  覆盖标记为false,执行下一次循环
						if(!iscover){
							continue;
						}
					}
					FileOutputStream out = new FileOutputStream(newfile);
					ftpClient.retrieveFile(remotePath + File.separator + file.getName(),
							out);
					out.flush();
					out.close();
					Map map = new HashMap();
					map.put("filename", file.getName());
					map.put("url", remotePath);
					fileList.add(map);
					logger.info("成功下载文件  " + remotePath +File.separator + file.getName()
							+ "成功");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileList;
	}

	/**
	 * 上传本地文件或文件夹到FTP 服务器上
	 * 
	 * @param ftpPath
	 * @param localpath
	 */
	public void upfile(String ftpPath, String localpath) {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		logger.info("上传本地文件 " + localpath + " 至FTP服务器的 " + ftpPath);
		try {
			logger.info("变更前工作空间:{},需要工作空间 :{}" , ftpClient.printWorkingDirectory(),ftpPath);
			
			
			if(!validateFileExists(ftpPath)) {
				logger.info("{} 不存在,开始创建",ftpPath );
				createFileDirectory("",ftpPath);
			};
			
			// 设置工作空间
			if (!ftpPath.equals(ftpClient.printWorkingDirectory())) {
				String ng_ftpPath = new String(ftpPath.getBytes("GBK"),"iso-8859-1"); 
				ftpClient.changeWorkingDirectory(ng_ftpPath);
			}
			logger.info("变更后工作空间:{}" , ftpClient.printWorkingDirectory());
			// 被动模式
			ftpClient.enterLocalPassiveMode();
			// 文件类型为二进制文件 图片上传需要
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			// 1M 缓存
			ftpClient.setBufferSize(1024);
			// 编码格式
			ftpClient.setControlEncoding("iso-8859-1");
			File file = new File(localpath);
			if (!file.exists()) {
				throw new ServiceException("需要上传的文件信息不存在");
			}
			if (file.isDirectory()) {
				FTPFile[] ftpfiles = ftpClient.listFiles(file.getName());
				// 判断文件夹是否存在,没有,则创建
				if (ftpfiles == null || ftpfiles.length <= 0) {
					String name = new String(file.getName().getBytes("GBK"),"iso-8859-1"); 
					ftpClient.makeDirectory(name);
				}
				File[] files = file.listFiles();
				for (File f : files) {
					String name = new String(f.getName().getBytes("GBK"),"iso-8859-1"); 
					
					
					upfile(ftpPath + "/" + file.getName(), localpath + File.separator
							+ f.getName());
				}

			} else {

				/* 未判断文件是否存在,默认为存在替换 */
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				ftpClient.enterLocalPassiveMode();
				FileInputStream in = new FileInputStream(file);
				String name = new String(file.getName().getBytes("GBK"),"iso-8859-1"); 
				ftpClient.storeFile(name, in);
				in.close();
				logger.info("文件" + file.getPath() + "上传完毕");
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * FTP 验证FTP路径对应文件是否存在
	 * 
	 * @param ftpPath
	 * @return 存在 true 不存在 false
	 * @throws IOException
	 */
	public Boolean validateFileExists(String ftpPath) throws IOException {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		// 被动模式
		ftpClient.enterLocalPassiveMode();
		// 文件类型为二进制文件 图片上传需要
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		// 1M 缓存
		ftpClient.setBufferSize(1024);
		// 编码格式
		ftpClient.setControlEncoding("utf-8");
		// 设定默认工作空间
		ftpClient.changeWorkingDirectory(defaultWorkSpace);
		
		String ng_ftpPath = new String(ftpPath.getBytes("GBK"),"iso-8859-1"); 
		
		FTPFile[] ftpfiles = ftpClient.listFiles(ng_ftpPath);
		// 判断文件是否存在,没有,返回false
		if (ftpfiles == null || ftpfiles.length <= 0) {
			return false;
		}
		return true;
	}

	/**
	 * 创建文件夹
	 * 
	 * @param ftpPath
	 * @return 文件夹存在或创建成功 true 否则 false
	 * @throws IOException
	 */
	public void createFileDirectory(String workspace, String directoryPath)
			throws IOException {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		// 被动模式
		ftpClient.enterLocalPassiveMode();
		// 文件类型为二进制文件 图片上传需要
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		// 1M 缓存
		ftpClient.setBufferSize(1024);
		// 编码格式
		ftpClient.setControlEncoding("utf-8");

		ftpClient.changeWorkingDirectory(workspace);
		 
		int x = directoryPath.indexOf("/");
		if (x < 0) {
			if (directoryPath != null && !"".equals(directoryPath)) {
				FTPFile[] ftpfiles = ftpClient.listFiles(directoryPath);
				if (ftpfiles == null || ftpfiles.length <= 0) {
					ftpClient.makeDirectory(new String(directoryPath.getBytes("GBK"),"iso-8859-1"));
					logger.info("工作空间" + workspace + "的文件" + directoryPath
							+ "已创建");
				} else {
					logger.info("工作空间" + workspace + "的文件" + directoryPath
							+ "已存在");
				}
			}
		} else {
			String directoryname = directoryPath.substring(0, x);
			String sy = directoryPath
					.substring((x + 1), directoryPath.length());
			if (directoryname != null && !"".equals(directoryname)) {
				FTPFile[] ftpfiles = ftpClient.listFiles(directoryname);
				if (ftpfiles == null || ftpfiles.length <= 0) {
					ftpClient.makeDirectory(new String(directoryname.getBytes("GBK"),"iso-8859-1"));
					logger.info("工作空间" + workspace + "的文件" + directoryname
							+ "已创建");
				} else {
					logger.info("工作空间" + workspace + "的文件" + directoryname
							+ "已存在");
				}
				workspace += "/" + directoryname;
			}
			createFileDirectory(workspace, sy);
		}
	}

	/**
	 * 切断 FTP 连接
	 */
	public void cut_connnect() {
		if (is_connected) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
				is_connected = false;
			} catch (IOException e) {
				throw new ServiceException("ftp 断开连接失败");
			}
		}
	}

	/**
	 * 设置超时时间,以秒为单位
	 * 
	 * @param defaultTimeoutSecond
	 * @param connectTimeoutSecond
	 * @param dataTimeoutSecond
	 */
	public void setOutTime(int defaultTimeout) {
		if (!this.is_connected) {
			throw new ServiceException("ftp 未连接或连接已断开,请初始化FTP工具类");
		}
		ftpClient.setDefaultTimeout(defaultTimeout * 1000);
		ftpClient.setConnectTimeout(defaultTimeout * 1000);
		ftpClient.setDataTimeout(defaultTimeout * 1000);
	}
	
	

	public static void main(String[] args) throws IOException {
		FTPUtil ftp = new FTPUtil(Ftputil.IMAGE_FTP_IP, Ftputil.IMAGE_FTP_PORT,
				Ftputil.IMAGE_FTP_USERNAME, Ftputil.IMAGE_FTP_USERPWD,
				Ftputil.FILE_FTP_DEFAULTDIREECTORY);
		
		//ftp.createFileDirectory("610702","8d314b246ece4507b7aec9436f965ba5");
		//ftp.createFileDirectory("610702","8d314b246ece4507b7aec9436f965ba5/身份证");
		ftp.upfile("/sjxm/ycdl/610702", "G:\\temp\\target\\610702\\8d314b246ece4507b7aec9436f965ba5");
	}
}