Java_FTP服务下载工具类

/**
 * 
 */
package com.sinosoft.common.ftp;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;


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 common.Logger;


public class FtpCollectionUtil {


	private String username;
	private String password;
	private String ftpHostName;
	private int port = 21;
	private FTPClient ftpClient = new FTPClient();
	private FileOutputStream fos = null;
	private Logger logger = Logger.getLogger(FtpCollectionUtil.class);
	private static String encoding = System.getProperty("file.encoding");


	public FtpCollectionUtil(String username, String password,
			String ftpHostName, int port) {
		super();
		this.username = username;
		this.password = password;
		this.ftpHostName = ftpHostName;
		this.port = port;
	}


	/**
	 * 建立连接
	 */
	private void connect() {
		try {
			logger.debug("开始连接");
			// 连接
			ftpClient.connect(ftpHostName, port);
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
			}
			// 登录
			ftpClient.login(username, password);
			ftpClient.setBufferSize(256);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);


//			ftpClient.setControlEncoding("utf8");
			logger.debug("登录成功!");
			logger.debug("开始登录!");
		} catch (SocketException e) {
			logger.error("", e);
		} catch (IOException e) {
			logger.error("", e);
		}


	}


	/**
	 * 关闭输入输出流
	 * 
	 * @param fos
	 */
	private void close(FileOutputStream fos) {
		try {
			if (fos != null) {
				fos.close();
			}


			ftpClient.logout();
			logger.info("退出登录");
			ftpClient.disconnect();
			logger.info("关闭连接");
		} catch (IOException e) {
			logger.error("", e);
		}
	}


	/**
	 * 下载文件
	 * 
	 * @param ftpFileName
	 * @param localDir
	 */
	public boolean down(String ftpFileName, String localDir) {
		connect();
		return downFileOrDir(ftpFileName, localDir);
	}


	private boolean downFileOrDir(String ftpFileName, String localDir) {
		boolean result = false;
		try {
			File file = new File(new String(ftpFileName.getBytes("iso-8859-1"), "GBK"));


			File temp = new File(localDir);


			if (!temp.exists()) {
				temp.mkdirs();
			}
			FTPFile[] listFiles = ftpClient.listFiles(ftpFileName);
			if(listFiles.length > 0){
				// 判断是否是目录
				if (isDir(ftpFileName)) {
					String[] names = ftpClient.listNames();
					for (int i = 0; i < names.length; i++) {
						System.out.println(names[i] + "^^^^^^^^^^^^^^");
						if (isDir(names[i])) {
							downFileOrDir(ftpFileName + '/' + names[i], localDir
									+ File.separator + names[i]);
							ftpClient.changeToParentDirectory();
						} else {
							File localfile = new File(localDir + File.separator
									+ names[i]);
							if (!localfile.exists()) {
								fos = new FileOutputStream(localfile);
								ftpClient.retrieveFile(names[i], fos);


							} else {
								logger.debug("开始删除文件");
								file.delete();
								logger.debug("文件已经删除");
								fos = new FileOutputStream(localfile);
								ftpClient.retrieveFile(ftpFileName, fos);


							}


						}
					}
				} else {


					File localfile = new File(localDir + File.separator
							+ file.getName());
					if (!localfile.exists()) {
						fos = new FileOutputStream(localfile);
						ftpClient.retrieveFile(ftpFileName, fos);


					} else {
						logger.debug("开始删除文件");
						file.delete();
						logger.debug("文件已经删除");
						fos = new FileOutputStream(localfile);
						ftpClient.retrieveFile(ftpFileName, fos);


					}
					ftpClient.changeToParentDirectory();


				}
				result = true;
				logger.info("下载成功!");
			}else{
				result = false;
				logger.info("目标文件不存在!");
			}
		} catch (SocketException e) {
			logger.error("连接失败!", e);
			return result;
		} catch (IOException e) {
			logger.error("下载失败!", e);
			return result;
		}finally{
			close(fos);
		}
		return result;
	}


	// 判断是否是目录
	public boolean isDir(String fileName) {
		try {
			// 切换目录,若当前是目录则返回true,否则返回true。
			boolean falg = ftpClient.changeWorkingDirectory(fileName);
			return falg;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("", e);
		}


		return false;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getFtpHostName() {
		return ftpHostName;
	}


	public void setFtpHostName(String ftpHostName) {
		this.ftpHostName = ftpHostName;
	}


	public int getPort() {
		return port;
	}


	public void setPort(int port) {
		this.port = port;
	}


	public static void main(String[] args) {

		
//		FtpCollectionUtil ftpUtil = new FtpCollectionUtil("ftpuser",
//				"sinosoftftp", "127.0.0.1", 21);


//		ftpUtil.down("/"+URLEncoder.encode("旬月雨量")+"/", "D://a");
		try {
//			String fileName = new String("/新建文件夹/".getBytes(encoding), "iso-8859-1");
//			System.out.println(fileName);
			System.out.println(ftpUtil.down(new String("/旬月雨量/5月降水.bmp".getBytes("GBK"), "iso-8859-1"), "D://a"));//英文可以下载
			System.out.println("encoding : " + encoding);
//			ftpUtil.down(URLEncoder.encode("/新建文件夹/"), "D://a");//中文可以下载
//			ftpUtil.down(fileName, "D://a");
		}
		catch (Exception e) {
			e.printStackTrace();
		}


	}


}

你可能感兴趣的:(JavaWeb)