Socket使用之Ftp上传工具类

阅读更多

涉及jar包:jftp.jar,jftp-bin-0_70.jar,log4j.jar(见附件)

1,FtpBaseUtils.java,主要作用获取IP,Port,username,password等等公共配置信息

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

import com.xxx.vo.FtpVO;

import cz.dhl.ftp.Ftp;
import cz.dhl.ftp.FtpConnect;

public class FtpBaseUtils {
	private static final Logger logger = Logger.getLogger(FtpUploadUtils.class);
	private static final FtpVO ftpVo = new FtpVO();
	static {
		ftpVo.setIp(PropertiesUtil.getValue("FTP.IP"));
		ftpVo.setPort(PropertiesUtil.getValue("FTP.PORT"));
		ftpVo.setUser(PropertiesUtil.getValue("FTP.USER"));
		ftpVo.setPassword(PropertiesUtil.getValue("FTP.PASSWORD"));
		ftpVo.setFtpDir(PropertiesUtil.getValue("FTP.DIR.TASKFile"));// ftp文件存放目录
		ftpVo.setLocalDir(FileUtils.getTaskFilePath());// 本地文件目录
	}

	public FtpBaseUtils() {
		super();
	}

	/**
	 * 取得ftp连接实例
	 * 
	 * @param ftpVo
	 *            ftp连接信息
	 * @return Ftp cz.dhl.ftp.Ftp实例
	 */
	protected static Ftp getFtpInstance(FtpVO ftpVo) {
		Ftp ftp = new Ftp();
		try {
			String ftpIp = ftpVo.getIp();
			String ftpUser = ftpVo.getUser();
			String ftpPsw = ftpVo.getPassword();
			Integer ftpPort = Integer.valueOf(ftpVo.getPort());

			logger.info("测试连接,ftp信息:" + ftpVo.toString());
			try {
				// 测试是否能连接ftp服务器,如果没有连接,返回失败信息
				Socket client = new Socket();
				System.out.println("ftp 连接开始..");
				SocketAddress addr = new InetSocketAddress(ftpIp, ftpPort);
				// 连接5秒后无法连接,返回失败信息
				client.connect(addr, 1500); // 超时时间为1.5秒
				System.out.println("ftp 断开连接..");
				client.close();
			} catch (Exception e) {
				// TODO: handle exception
				throw new Exception("ftp链接失败:" + e.getMessage());
			}

			/* connect & login to host */
			FtpConnect ftpConn = FtpConnect.newConnect("ftp://" + ftpIp);
			ftpConn.setUserName(ftpUser);
			ftpConn.setPassWord(ftpPsw);
			ftpConn.setPortNum(ftpPort);
			ftp.connect(ftpConn);
		} catch (Exception e) {
			ftp = null;
			logger.error("连接失败!", e);
		}
		return ftp;
	}

	/**
	 * 获取FTP配置信息:ip,port,上传目录。。。
	 * 
	 * @return FtpVO
	 */

	protected static FtpVO getFtpCommonConfigVO() {
		return ftpVo;
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath
	 *            文件路径名
	 */
	protected boolean delFile(String filePath) {
		// TODO Auto-generated method stub
		try {
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			} else {
				return false;
			}
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("删除文件失败:" + e.getMessage());
			return false;
		}
	}

}

  

2 ,FtpUploadUtils.java负责具体上传操作

入口:uploadFile(String fileName) filename包括可获取到的完整的路径及文件名,其方法说明见注释

执行上传操作:doFtpUploadFile

 

import org.apache.log4j.Logger;

import com.xxx.vo.FtpVO;

import cz.dhl.ftp.Ftp;
import cz.dhl.ftp.FtpFile;
import cz.dhl.io.CoFile;
import cz.dhl.io.CoLoad;
import cz.dhl.io.LocalFile;

public class FtpUploadUtils extends FtpBaseUtils {
	private static final Logger logger = Logger.getLogger(FtpUploadUtils.class);

	/**
	 * 上传文件到FTP服务 1.先上传到WEB服务器临时目录 2.从临时目录上传到FTP服务器 3.删除临时文件 :fileName:完整路径+文件名
	 * 
	 * @throws Exception
	 */
	public static String uploadFile(String fileName) {
		logger.info("##############################");
		logger.info("开始准备上传文件:" + fileName);
		FtpVO ftpVO = getFtpCommonConfigVO();// 获取公共配置信息:帐号,端口
		ftpVO.setFtpFileName(fileName);
		ftpVO.setLocalFileName(fileName);
		logger.info("获取ftp配置信息:" + JsonUtils.toJson(ftpVO, false));
		Ftp ftp = getFtpInstance(ftpVO);// 获取FTP实例
		String message = doFtpUploadFile(ftp, ftpVO);
		// 删除临时文件
		/*
		 * if (super.delFile(filePathName)) { logger.info("删除临时文件成功." +
		 * filePathName); } else { logger.warn("删除临时文件失败." + filePathName); }
		 */
		logger.info("########结束文件上传######");
		return message;
	}

	private static String doFtpUploadFile(Ftp ftp, FtpVO ftpVo) {
		logger.info("##### 【开始】文件上传。。。。");
		String ftpDir = ftpVo.getFtpDir();
		String ftpFileName = ftpVo.getFtpFileName();
		String localDir = ftpVo.getLocalDir();
		String localFileName = ftpVo.getLocalFileName();
		String message = localFileName + "上传成功!";
		try {
			if (ftp == null) {
				throw new Exception("ftp连接失败!FTP信息:" + ftpVo.toString());
			}

			CoFile tmpfile = new LocalFile(localDir + localFileName); // 本地文件
			if (!tmpfile.exists()) {// 检测本地文件是否存在
				logger.info("文件【" + localDir + localFileName + "】不存在");
				message = "###文件" + localDir + localFileName + "】不存在";
			}

			CoFile ftpFolder = new FtpFile(ftpDir, ftp); // 远程文件夹
			CoFile ftpFile = new FtpFile(ftpDir + ftpFileName, ftp); // 远程文件名

			if (!ftpFolder.exists()) {// 检测ftp目录是否存在
				ftpFolder.mkdir();
				logger.warn("folder is not exist:" + ftpDir);
			}
			// copy file to the other position
			logger.info(">>文件是否存在:" + ftpFile.exists());
			if (!ftpFile.exists()) {// 检测ftp文件是否存在
				if (!CoLoad.copy(ftpFile, tmpfile)) {
					logger.error("文件从web服务器上传到FTP服务器失败.FTP信息:"
							+ ftpVo.toString());
					message = localDir + localFileName
							+ "文件从web服务器上传到FTP服务器失败.FTP信息:" + ftpVo.toString();
				} else {
					message = localDir + localFileName + "文件上传成功";
					logger.info(message);
				}
			} else {
				message = localDir + localFileName + "已存在,上传失败! FTP信息:"
						+ ftpVo.toString();
				logger.warn(message);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = localDir + localFileName + "上传失败:" + e.getMessage();
		} finally {
			ftp.disconnect();
		}
		logger.info("上传返回信息:" + message);
		logger.info("##### 【结束】文件上传操作。。。。");
		return message;
	}
}

 

 

3,PropertiesUtil.java:负责配置文件加载(可选,去掉之后需要修改相应代码及配置)

 

import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * A simple base implementation of Properties file
 * 
 * @author Eagles 2005-12-22
 */
public final class PropertiesUtil {
	protected static Logger logger = Logger.getLogger(PropertiesUtil.class);

	/**
	 * 配置文件名称
	 */
	private static final String FILENAME = "config.properties";
	private static Properties prop = null;

	/**
	 * 初始化加载配置文件
	 * 
	 * @return:an instance from Properties
	 */
	private static synchronized Properties getProperties() {
		logger.debug("init an instance from the Properties");
		if (prop == null) {
			prop = new Properties();
			try {
				prop.load(PropertiesUtil.class.getClassLoader()
						.getResourceAsStream(FILENAME));
				return prop;
			} catch (IOException ex) {
				logger.error("init an instance from the Properties error:"
						+ ex.getMessage());
				return null;
			}
		}
		return prop;
	}

	public static String getValue(String param) {
		String result = getProperties().getProperty(param);
		return result == null ? "" : result;
	}

	public static void main(String[] args) {
		System.out.println(PropertiesUtil.getValue("ftpPassword"));
	}

}

 

 对应加载的配置文件

 

#----------------------------------------------
# Ftp Config
#----------------------------------------------
FTP.IP=192.168.7.161
FTP.USER=root
FTP.PASSWORD=etone
FTP.PORT=21
#ftp存放目录
FTP.DIR.TASKFile=/data/
#本地文件存放目录
LOCAL.DIR.TEMP.TASKFile=/temp/
 

存放ftp配置属性VO(可选,去掉之后需要修改相应代码及配置)

 

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * ftp相关数据封装类
 * @author Administrator
 *
 */
public class FtpVO {
	
	private String ip;
	private int port;
	private String user;
	private String password;
	private String ftpDir;
	private String ftpFileName;
	
	private String localDir;
	private String localFileName;
	
	private boolean isDelOldFile;
	private boolean isReName;
	
	public String getFtpDir() {
		return ftpDir;
	}
	public void setFtpDir(String ftpDir) {
		this.ftpDir = ftpDir;
	}
	public String getFtpFileName() {
		return ftpFileName;
	}
	public void setFtpFileName(String ftpFileName) {
		this.ftpFileName = ftpFileName;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public boolean isDelOldFile() {
		return isDelOldFile;
	}
	public void setDelOldFile(boolean isDelOldFile) {
		this.isDelOldFile = isDelOldFile;
	}
	public boolean isReName() {
		return isReName;
	}
	public void setReName(boolean isReName) {
		this.isReName = isReName;
	}
	public String getLocalDir() {
		return localDir;
	}
	public void setLocalDir(String localDir) {
		this.localDir = localDir;
	}
	public String getLocalFileName() {
		return localFileName;
	}
	public void setLocalFileName(String localFileName) {
		this.localFileName = localFileName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}


}
 

4,FileUtils.java辅助类(可选,可以把此部分代码移到FtpBaseUtils.java中,writeToFile()可删掉

 

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

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

	public static final String taskFilePath = PropertiesUtil
			.getValue("LOCAL.DIR.TEMP.TASKFile");
	public static final String prefix = "test_";
	public static final String suffix = ".txt";
	public static String webRoot = "";
	static {
		// 获取webRoot目录
		webRoot = FileUtils.class.getClassLoader().getResource("").toString();// file:/D:/publish/Elvis_GZ_V4/WEB-INF/classes/
		if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			webRoot = webRoot.replace("file:/", "");// file:/D:/publish/Elvis_GZ_V4/WEB-INF/classes/
		} else {
			webRoot = webRoot.replace("file:", "");// file:/opt/web/Elvis_GZ_V4/WEB-INF/classes/
		}
		webRoot = webRoot.replace("/WEB-INF/classes/", "");
		webRoot = webRoot.replace("%20", " ");
	}

	public static final String getWebRoot() {
		return webRoot;
	}

	public static final String getTaskFilePath() {
		return getWebRoot() + taskFilePath;
	}

	/**
	 * 内容写入指定文件
	 * 
	 * @param content
	 * @param fileName
	 */
	public static void writeToFile(String content, String fileName) {
		System.out.println("sssss");
		BufferedWriter buffWriter = null;
		try {
			buffWriter = new BufferedWriter(new FileWriter(fileName, true));
			buffWriter.write(content);
			buffWriter.newLine();
		} catch (IOException e) {
			logger.error("写入文件【" + fileName + "】失败:" + e.getMessage(), e);
		} finally {
			if (null != buffWriter) {
				try {
					buffWriter.flush();
					buffWriter.close();
				} catch (IOException e) {
					logger.error("close bufferWriter failed:" + e.getMessage(),
							e);
				}

			}
			System.out.println("eeeee");
		}
	}
}
 

 

 

  • jftp.jar (77.6 KB)
  • 下载次数: 48
  • jftp-bin-0_70.jar (38 KB)
  • 下载次数: 44
  • log4j-1.2.15.jar (382.7 KB)
  • 下载次数: 26

你可能感兴趣的:(Socket使用之Ftp上传工具类)