FTPUtils.java 8.05 KB
package com.topdraw.sohu.utils;

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 java.io.*;

public class FTPUtils {
	private static final Logger logger = LoggerFactory
			.getLogger(FTPUtils.class);

	private final String PROJECT_PATH = this.getClass().getClassLoader().getResource("../../") == null ?
			(System.getProperty("user.dir").endsWith("/") ? System.getProperty("user.dir")
					: System.getProperty("user.dir") + "/")
			: this.getClass().getClassLoader().getResource("../../").getPath();

	/**
	* Description: 向FTP服务器上传文件
	* @param url FTP服务器hostname
	* @param port FTP服务器端口
	* @param username FTP登录账号
	* @param password FTP登录密码
	* @param path FTP服务器保存目录
	* @param filename 上传到FTP服务器上的文件名
	* @param input 输入流
	* @return 成功返回true,否则返回false
	*/ 
	public boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { 
	    boolean success = false; 
	    FTPClient ftp = new FTPClient(); 
	    try { 
	        int reply; 
	        ftp.connect(url, port);//连接FTP服务器 
	        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 
	        ftp.login(username, password);//登录 
	        reply = ftp.getReplyCode(); 
	        System.out.println("ReplyCode: " + reply);
	        if (!FTPReply.isPositiveCompletion(reply)) { 
	            ftp.disconnect(); 
	            return success; 
	        } 
	        ftp.changeWorkingDirectory(path); 
	        ftp.storeFile(filename, input);          
	         
	        input.close(); 
	        ftp.logout(); 
	        success = true; 
	    } catch (IOException e) { 
	        e.printStackTrace(); 
	    } finally { 
	        if (ftp.isConnected()) { 
	            try { 
	                ftp.disconnect(); 
	            } catch (IOException ioe) { 
	            } 
	        } 
	    } 
	    return success; 
	}
	
	/**
	* Description: 从FTP服务器下载文件
	* @param url FTP服务器hostname
	* @param port FTP服务器端口
	* @param username FTP登录账号
	* @param password FTP登录密码
	* @param remotePath FTP服务器上的相对路径
	* @param fileName 要下载的文件名
	* @param localPath 下载后保存到本地的路径
	* @return
	*/ 
	public static boolean downFile(
			String url, int port, String username, String password, String remotePath, String fileName,
			String localPath) {
	    boolean success = false; 
	    FTPClient ftp = new FTPClient(); 
	    try { 
	        int reply;
	        ftp.setConnectTimeout(10 * 1000);
	        ftp.connect(url, port); 
	        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 
	        ftp.login(username, password);//登录 
	        ftp.setBufferSize(102400);
	        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
	        reply = ftp.getReplyCode(); 
	        System.out.println("ReplyCode: " + reply);
	        if (!FTPReply.isPositiveCompletion(reply)) { 
	        	logger.info("isPositiveCompletion");
	            ftp.disconnect(); 
	            return success; 
	        }
	        logger.info("remotePath: " + remotePath);
	        ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录 
	        ftp.enterLocalPassiveMode();
	        FTPFile[] fs = ftp.listFiles(); 
	        for (FTPFile ff:fs) { 
	            if (ff.getName().equals(fileName)) {
		            File localFile = new File(localPath + "/" + ff.getName());
		            logger.info("file size: " + ff.getSize());
	                 
	                OutputStream is = new FileOutputStream(localFile);  
	                ftp.retrieveFile(ff.getName(), is); 
	                is.close();
	                logger.info("download file size: " + localFile.length());
	                if (ff.getSize() == localFile.length()) {
		                success = true;
	                } else {
	                	logger.info("file size mismatch: " + ff.getSize() + " -> " + localPath.length());
	                }
	                break;
	            }
	        }
	        ftp.logout();
	    } catch (IOException e) {
	        e.printStackTrace();
		    success = false;
	    } finally {
	        if (ftp.isConnected()) { 
	            try { 
	                ftp.disconnect(); 
	            } catch (IOException ioe) {
	            	ioe.printStackTrace();
	            } 
	        } 
	    } 
	    return success;
	}
	
	public String downFile(String strFtpPath, String strRelativePath) {
		String strUrl = "", strUserName = "", strPassWord = "", strRemotePath = "", strFileName = "", strLocalPath = "";
		int iPort = 21;
		// 截取FTP地址
		final String strFtpFlag = "ftp://";
		if (strFtpPath != null && strFtpPath.length() > 0 && strFtpPath.toLowerCase().contains(strFtpFlag)) {
			// 首先去掉FTP
			final String cutedFtp = strFtpPath.substring(strFtpPath.indexOf(strFtpFlag) + strFtpFlag.length());
			// 首先截取用户名、密码、ip、端口
			String str4 = "";
			if (cutedFtp.indexOf("/") != -1) {
				str4 = cutedFtp.substring(0, cutedFtp.indexOf("/"));
			} else {
				str4 = cutedFtp;
			}
			// 截取用户名、密码
			String strUsernameAndPwd = str4.substring(0, str4.indexOf("@"));
			
			// 截取ip、端口
			String strIpAndPort = str4.substring(str4.indexOf("@") + 1);
			
			// 开始获取ip和端口
			if (!"".equals(strIpAndPort)) {
				if (strIpAndPort.indexOf(":") != -1) {
					strUrl = strIpAndPort.substring(0, strIpAndPort.indexOf(":"));
					String strPort = strIpAndPort.substring(strIpAndPort.indexOf(":") + 1, strIpAndPort.length());
					if (strPort != null) {
						iPort = Integer.parseInt(strPort);
					}
				} else {
					// 如果没有端口只获取IP
					strUrl = strIpAndPort;
				}
			}
			
			// 开始获取用户名和密码
			if (!"".equals(strUsernameAndPwd)) {
				strUserName = strUsernameAndPwd.substring(0, strUsernameAndPwd.indexOf(":"));
				strPassWord = strUsernameAndPwd.substring(strUsernameAndPwd.indexOf(":") + 1);
			}

			// 截取ftp文件路径和文件名
			String strFileNameAndPath = "";
			if (cutedFtp.indexOf("/") != -1) {
				strFileNameAndPath = cutedFtp.substring(cutedFtp.indexOf("/") + 1, cutedFtp.length());
			} else {
				strFileNameAndPath = "";
			}
			// 开始获取ftp文件路径和文件名
			if (!"".equals(strIpAndPort)) {
				if (strFileNameAndPath.indexOf("/") != -1) {
					strRemotePath = strFileNameAndPath.substring(0, strFileNameAndPath.lastIndexOf("/"));
					strFileName = strFileNameAndPath.substring(strFileNameAndPath.lastIndexOf("/") + 1,
							strFileNameAndPath.length());
				} else {
					strFileName = strFileNameAndPath;
				}
			}
		}
		
		strLocalPath = PROJECT_PATH + strRelativePath + strFileName;
		logger.info("file download target path: " + strLocalPath);
		File file = new File(strLocalPath);
		if (!file.isDirectory()) { // 目录不存在
			String[] aPathSegments = strLocalPath.split("/");
			String strWalkThroughPath = "/";
			for (int i = 0; i < aPathSegments.length - 1; i++) {
				strWalkThroughPath = strWalkThroughPath + "/" + aPathSegments[i];
				file = new File(strWalkThroughPath);
				if (!file.isDirectory()) {
					file.mkdir();
				}
			}
		}
		
		boolean b = FTPUtils.downFile(strUrl, iPort, strUserName, strPassWord, strRemotePath, strFileName, 
				PROJECT_PATH + strRelativePath);
		if (!b) {
			// 下载失败
			logger.info("file download error: " + strLocalPath);
			return "";
		} else {
			logger.info("file saved: " + strLocalPath);
		}
		return strLocalPath;
	}
	
	public static void main(String[] args) {
		try {
	        //FileInputStream in = new FileInputStream(new File("D:/adv.txt"));
	        //boolean flag = uploadFile("10.50.127.181", 21, "root", "bestvwin", "/tmp", "adv.txt", in);
	        //boolean flag = downFile("172.25.44.26", 21, "wacos", "wacos", "/opt/wacos/CTMSData/picture/2018/02/07",
			 //       "20180207112330_320029.jpg", "");
	        //System.out.println(flag);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
}