MyFtpClient 1.8下的ftp工具类

public class MyFtpClient {

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

public FTPClient ftp = null;

private String ip = "";

private int port = 21;

private String username = "";

private String password = "";

public MyFtpClient() {
	ftp = new FTPClient();
}


/**   
* @Function: MyFtpClient.java
* @Description: 该函数的功能描述
* @param:参数描述
*/
public MyFtpClient(String ip, String username, String password) {
	super();
	this.ip = ip;
	this.username = username;
	this.password = password;
	
	try {
		connect();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}


public boolean uploadFile(String serverpath, String file) {
	// 初始表示上传失败
	boolean success = false;
	// 创建FTPClient对象
	try {
		// 设置PassiveMode传输
		if (!ftp.isConnected()) {
			boolean b = connect();
			if (b == false) {
				return success;
			}
		}
		/*
		 * int reply; reply = ftp.getReplyCode(); if
		 * (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; }
		 */
		// 转到指定上传目录
		serverpath = gbkToIso8859(serverpath);
		if (!checkPathExist(iso8859ToGbk(serverpath)))
			return false;
		if (!ftp.changeWorkingDirectory(iso8859ToGbk(serverpath))) {
			System.err.print("远程无此目录");
			return false;
		}

		// 输入流
		InputStream input = null;
		try {
			file = gbkToIso8859(file);
			input = new FileInputStream(iso8859ToGbk(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 将上传文件存储到指定目录
		file = iso8859ToGbk(file);
		if (!ftp.storeFile(iso8859ToGbk(serverpath) + "/" + iso8859ToGbk(getFilename(file)), input)) {
			return false;
		}

		// 关闭输入流
		input.close();
		// 退出ftp

		// 表示上传成功
		success = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			ftp.logout();
			disconnect();
		} catch (IOException ioe) {
		}

	}
	return success;
}

/**
 * 从FTP服务器下载文件
 * 
 * @param ip
 *            FTP服务器ip e.g:
 * @param port
 *            FTP服务器端口
 * @param username
 *            FTP登录账号
 * @param password
 *            FTP登录密码
 * @param serverpath
 *            FTP服务器上的相对路径 默认缺省时指向主目录
 * @param fileName
 *            要下载的文件名
 * @param localPath
 *            下载后保存到本地的路径 不含文件名
 * @return 成功返回true,否则返回false
 */
public String downFile(String serverpath, String fileName, String localPath) { // 初始表示下载失败
	String msg = ProductErrorEnum.Pro_FileDownload_Defeat_Tip.getCode();
	// 创建FTPClient对象
	try {
		if (!ftp.isConnected()) {
			boolean b = connect();
			if (b == false) {
				return msg;
			}
			logger.info("服务器已连接");
		}
		/*
		 * int reply; reply = ftp.getReplyCode(); if
		 * (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; }
		 */

		// 转到指定下载目录
		logger.info("文件路径是"+serverpath);
		serverpath = gbkToIso8859(serverpath);
		//logger.info("转码后路径是"+serverpath);
		ftp.changeWorkingDirectory(this.iso8859ToGbk(serverpath));
		// 列出该目录下所有文件
		FTPFile[] fs = ftp.listFiles();
		fileName = this.gbkToIso8859(fileName);
		localPath = this.gbkToIso8859(localPath);

		// 遍历所有文件,找到指定的文件

		for (int i = 0; i < fs.length; i++) {
			FTPFile f = fs[i];

			logger.info("文件服务器上的文件是"+f);
			logger.info("要下载文件名(库里查询)转码前名字是"+fileName);
			if (f.getName().equals(iso8859ToGbk(fileName))) {
				logger.info("iso8859ToGbk要下载文件名(库里查询)转码后名字在文件服务器上找到了");
				// 根据绝对路径初始化文件
				File localFile = new File(iso8859ToGbk(localPath) + File.separator + f.getName());
				File localFileDir = new File(iso8859ToGbk(localPath));
				// 保存路径不存在时创建
				if (!localFileDir.exists()) {
					localFileDir.mkdirs();
				}
				// 输出流
				OutputStream is = new FileOutputStream(localFile);
				// 下载文件
				//ftp.retrieveFile(f.getName(), is);
				
				String propertyForPlatform2="";
				String propertyForPlatform1="";
				try {
					propertyForPlatform1 = SysConfig.getPropertyForPlatform("Persionalencoding1");
					propertyForPlatform2 = SysConfig.getPropertyForPlatform("Persionalencoding2");
				} catch (Exception e) {
					propertyForPlatform1="GBK";
					propertyForPlatform2="ISO-8859-1";
					e.printStackTrace();
				}
				ftp.retrieveFile(new String(f.getName().getBytes(propertyForPlatform1), propertyForPlatform2), is);
				is.close();
				// 下载成功
				msg = ProductErrorEnum.Pro_FileDownload_Success_Tip.getCode();
				logger.info("文件下载成功"+msg);
			}
			
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			ftp.logout();
			disconnect();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	return msg;
}


public String downFileUTF8(String serverpath, String fileName, String localPath) { // 初始表示下载失败
	String msg = ProductErrorEnum.Pro_FileDownload_Defeat_Tip.getCode();
	// 创建FTPClient对象
	try {
		if (!ftp.isConnected()) {
			boolean b = connectUtf8();
			if (b == false) {
				return msg;
			}
			logger.info("服务器已连接");
		}
		/*
		 * int reply; reply = ftp.getReplyCode(); if
		 * (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; }
		 */

		// 转到指定下载目录
		logger.info("文件路径是"+serverpath);
		serverpath = Utf8ToIso8859(serverpath);
		//logger.info("转码后路径是"+serverpath);
		ftp.changeWorkingDirectory(this.iso8859ToUtf8(serverpath));
		// 列出该目录下所有文件
		FTPFile[] fs = ftp.listFiles();
		fileName = this.Utf8ToIso8859(fileName);
		localPath = this.Utf8ToIso8859(localPath);

		// 遍历所有文件,找到指定的文件

		for (int i = 0; i < fs.length; i++) {
			FTPFile f = fs[i];

			logger.info("文件服务器上的文件是"+f);
			logger.info("要下载文件名(库里查询)转码前名字是"+fileName);
			logger.info("要下载文件名(库里查询)转码后名字iso8859ToUtf8是"+fileName);
			if (f.getName().equals(iso8859ToUtf8(fileName))) {
				logger.info("iso8859ToUtf8要下载文件名(库里查询)转码后名字在文件服务器上找到了");
				// 根据绝对路径初始化文件
				File localFile = new File(iso8859ToUtf8(localPath) + File.separator + f.getName());
				File localFileDir = new File(iso8859ToUtf8(localPath));
				// 保存路径不存在时创建
				if (!localFileDir.exists()) {
					localFileDir.mkdirs();
				}
				// 输出流
				OutputStream is = new FileOutputStream(localFile);
				// 下载文件
				ftp.retrieveFile(f.getName(), is);
				is.close();
				// 下载成功
				msg = ProductErrorEnum.Pro_FileDownload_Success_Tip.getCode();
				logger.info("文件下载成功"+msg);
			}
			
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			ftp.logout();
			disconnect();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	return msg;
}

/**
 * 
 * 查找指定目录是否存在 不存在创建目录
 * 
 * @param FTPClient
 *            ftpClient 要检查的FTP服务器
 * @param String
 *            filePath 要查找的目录
 * @return boolean:存在:true,不存在:false
 * @throws IOException
 */
private boolean checkPathExist(String filePath) throws IOException {
	boolean existFlag = false;
	try {
		if (filePath != null && !filePath.equals("")) {
			if (filePath.indexOf("/") != -1) {
				int index = 0;
				while ((index = filePath.indexOf("/")) != -1) {
					if (!ftp.changeWorkingDirectory(filePath.substring(0, index))) {
						ftp.makeDirectory(filePath.substring(0, index));
					}
					ftp.changeWorkingDirectory(filePath.substring(0, index));
					filePath = filePath.substring(index + 1, filePath.length());
				}
				if (!filePath.equals("")) {
					if (!ftp.changeWorkingDirectory(filePath)) {
						ftp.makeDirectory(filePath);
					}
				}
			}
			existFlag = true;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return existFlag;
}

/**
 * 根据绝对路径获得文件名
 * 
 * @param file
 *            文件绝对路径 e.g: e.g: E:/log/log.txt OR E:\\log\\log.txt
 * @return 转码后的文件名
 */
private String getFilename(String file) {
	// 文件名
	String filename = "";
	if (file != null && !file.equals("")) {
		file = file.replaceAll(Matcher.quoteReplacement("\\"), "/");
		String[] strs = file.split("/");
		filename = strs[strs.length - 1];
	}
	filename = gbkToIso8859(filename);// 转码
	return filename;
}


/**
 * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
 * 
 * @param obj
 * @return
 */
private String iso8859ToGbk(Object obj) {
	try {
		if (obj == null)
			return "";
		else {
			String str = new String(obj.toString().getBytes("iso-8859-1"), "GBK");
			return str;

		}
	} catch (Exception e) {
		return "";
	}
}

/**
 * 转码[GBK -> ISO-8859-1] 不同的平台需要不同的转码
 * 
 * @param obj
 * @return
 */
private String gbkToIso8859(Object obj) {
	try {
		if (obj == null)
			return "";
		else
			return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
	} catch (Exception e) {
		return "";
	}
}

/**
 * 转码[ISO-8859-1 -> UTF-8] 不同的平台需要不同的转码
 * 
 * @param obj
 * @return
 */
private String iso8859ToUtf8(Object obj) {
	try {
		if (obj == null)
			return "";
		else {
			String str = new String(obj.toString().getBytes("iso-8859-1"), "UTF-8");
			return str;

		}
	} catch (Exception e) {
		return "";
	}
}

/**
 * 转码[UTF-8 -> ISO-8859-1] 不同的平台需要不同的转码
 * 
 * @param obj
 * @return
 */
private String Utf8ToIso8859(Object obj) {
	try {
		if (obj == null)
			return "";
		else
			return new String(obj.toString().getBytes("UTF-8"), "iso-8859-1");
	} catch (Exception e) {
		return "";
	}
}

/** */
/**
 * 连接到FTP服务器
 * 
 * @param hostname
 *            主机名
 * @param port
 *            端口
 * @param username
 *            用户名
 * @param password
 *            密码
 * @return 是否连接成功
 * @throws IOException
 */
private boolean connect(String hostname, int port, String username, String password) throws IOException {
	
	ftp.setControlEncoding("GBK");
	//UTF-8  GBK
	FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
	//SYST_UNIX  SYST_NT
	conf.setServerLanguageCode("zh");
	ftp.connect(hostname, port);
	int reply = ftp.getReplyCode();
	if (FTPReply.isPositiveCompletion(reply)) {
		if (ftp.login(username, password)) {
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();

			return true;
		}
	}
	disconnect();
	return false;
}

public boolean connect() throws IOException {
	return connect(ip, port, username, password);
}

private boolean connectUtf8(String hostname, int port, String username, String password) throws IOException {

	ftp.setControlEncoding("UTF-8");
	//UTF-8  GBK
	FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
	//SYST_UNIX  SYST_NT
	conf.setServerLanguageCode("zh");
	ftp.connect(hostname, port);
	int reply = ftp.getReplyCode();
	if (FTPReply.isPositiveCompletion(reply)) {
		if (ftp.login(username, password)) {
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();

			return true;
		}
	}
	disconnect();
	return false;
}

public boolean connectUtf8() throws IOException {
	return connectUtf8(ip, port, username, password);
}

/**
 * 断开与远程服务器的连接
 * 
 * @throws IOException
 */
public void disconnect() throws IOException {
	if (ftp.isConnected()) {
		ftp.disconnect();
	}
}

public void setFtp(FTPClient ftp) {
	this.ftp = ftp;
}

public void setIp(String ip) {
	this.ip = ip;
}

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

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

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


public static void main(String[] args) {
	MyFtpClient ftpClient = new MyFtpClient();
	ftpClient.setIp("10.8.206.1");
	ftpClient.setUsername("ftpuser");
	ftpClient.setPassword("123");

	String fileName="附件2020.doc";
	String serverpath="/weblogic/ftp/202010";
	String localPath="out";
	String downFile = ftpClient.downFile(serverpath, fileName, localPath);
	logger.info("输出结果是"+downFile);
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章