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);
}

}

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