首页 > 代码库 > FTP--实践可用

FTP--实践可用

package sunline.common.logic.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

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.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.sunline.flow.base.annotation.Bizlet;

/**
 * 
 * @author niucheng created 2017/05/08
 * 
 */
public class FTPUtil {
	private static Logger logger = Logger.getLogger(FTPUtil.class);
	private static FTPClient ftpClient = null;

	// 连接FTP服务器
	@Bizlet("连接FTP服务器")
	public static boolean connect(String host, int port, String username,
			String password) {
		ftpClient = new FTPClient();
		boolean loginFlag = false;
		try {
			ftpClient.setControlEncoding("GBK");
			// 连接远程主机
			ftpClient.connect(host, port);
			if (password == null) {
				password = "";
			}
			// 登陆远程主机
			loginFlag = ftpClient.login(username, password);
			ftpClient.setDataTimeout(120000);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			if (loginFlag == false) {
				logger.info("登录FTP远程主机失败");
				ftpClient.logout();
				if (ftpClient.isConnected()) {
					ftpClient.disconnect();
				}
				throw new Exception("登录失败!");
			} else {
				logger.info("登录FTP远程主机成功");
				return true;
			}
		} catch (Exception e) {
			new Exception("连接FTP服务器出错");
		}
		return false;
	}

	/**
	 * 注意:上传FTP时的绝对路径包括/dir/文件名,文件名跟本地要上传的文件名对应,切记切记
	 * @param local
	 *            本地文件绝对路径
	 * @param remoteDirectory
	 *            远程FTP文件绝对路径(包括文件名)
	 * @param localFileName
	 * @return
	 * @throws Exception
	 */
	@Bizlet(value = "http://www.mamicode.com/上传文件")
	public static boolean upLoadFileFtp(String local, String remoteDirectory,
			String localFileName) throws Exception {
		InputStream is = null;
		boolean result = false;
		if (!ftpClient.isConnected()) {
			logger.info("FTP未连接");
			return false;
		}
		try {
			if (remoteDirectory != null && local != null) {
				//注意:这里的本地文件路径和FTP文件保存路径都是绝对路径(包括文件名,切记)
				remoteDirectory = new String((remoteDirectory + localFileName).getBytes("GBK"),
						"ISO-8859-1");
				local = new String((local + localFileName).getBytes("GBK"),
						"ISO-8859-1");
				is = new FileInputStream(new File(local));
				// 转移到FTP服务器目录
				boolean changeWorkingDirectory = ftpClient
						.changeWorkingDirectory(remoteDirectory);
				result = ftpClient.storeFile(remoteDirectory, is);
				System.out.println("上传结果" + localFileName + result);
				if (result) {
					logger.info("文件" + localFileName + "上传成功");
				} else {
					logger.info("文件" + localFileName + "上传失败");
				}
			}
		} catch (Exception e) {
			new Exception("文件上传出错");
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@Bizlet("批量上传文件")
	public static boolean bacthUploadFileFtp(String remoteDirectory,
			String localPath) {
		boolean result = false;
		try {
			File file = new File(localPath);
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				// bak代表备份文件,-1代表不是备份文件
				if (files[i].isFile()
						&& files[i].getName().indexOf("bak") == -1) {
					result = upLoadFileFtp(localPath, remoteDirectory,
							files[i].getName());
				}
			}
			if (result == true) {
				logger.info("批量上传文件成功");
			} else {
				logger.info("批量上传文件失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	// 判断FTP目录是否存在
	public static boolean isDirExist(String dir) {
		boolean flag = false;
		try {
			FTPFile[] ftpFileArr = ftpClient.listFiles(dir);
			System.out.println("目录不存在---------" + ftpFileArr.length);
			if (ftpFileArr.length > 0) {
				flag = true;
			}
		} catch (IOException e1) {
			return false;
		}
		return flag;
	}

	// 创建FTP目录
	public static boolean creatFtpDir(String ftpDir) {
		boolean flag = false;
		try {
			// 如果目录不存在就创建目录
			if (isDirExist(ftpDir) == false) {
				flag = ftpClient.makeDirectory(ftpDir);
				System.out.println("创建目录" + ftpDir + "结果:" + flag);
			}
		} catch (Exception e) {
			new Exception("创建 " + ftpDir + "目录出错");
		}
		return flag;
	}

	/*public static void main(String[] args) throws Exception {
		boolean connect = connect("160.161.12.122", 21, "sn", "sn");
		System.out.println("连接是否成功:" + connect);
		String remoteDirectory = "/home/sncx/ftp_data/bach/ibs/";
		String localPath = "D:/upload/";
		boolean up = bacthUploadFileFtp(remoteDirectory, localPath);

		System.out.println("上传结果---" + up);
	}*/
}

  

FTP--实践可用