上传见:Socket使用之Ftp上传工具类,除了FtpDownloadUtils.java之外,其他java文件和上传都一样
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; } } }
入口:ftpDownloadFile(String fileName)filename包括可获取到的完整的路径及文件名,其方法说明见注释
执行下载操作:doFtpDownFile
import java.io.File; import org.apache.log4j.Logger; import com.etone.if1Interface.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 FtpDownloadUtils extends FtpBaseUtils { private static final Logger logger = Logger .getLogger(FtpDownloadUtils.class); /** * fileName=路径+文件名 * * @param fileNames */ public String ftpDownloadFile(String fileName) { FtpVO ftpVO = getFtpCommonConfigVO();// 获取公共配置信息:帐号,端口 ftpVO.setFtpFileName(fileName);// 设置要下载的文件 ftpVO.setLocalFileName(fileName);// 存放路径及名称 Ftp ftp = getFtpInstance(ftpVO);// 获取FTP实例 String message = doFtpDownFile(ftp, ftpVO); return message; } /** * 执行下载操作: FtpVO此对象里属性包含ip,用户名,帐号,存储目录等等 * * @param ftp * @param ftpVo * @return */ private String doFtpDownFile(Ftp ftp, FtpVO ftpVo) { String ftpDir = ftpVo.getFtpDir(); String ftpFileName = ftpVo.getFtpFileName(); String localDir = ftpVo.getLocalDir(); String localFileName = ftpVo.getLocalFileName(); String message = ftpFileName + "下载成功!"; try { if (ftp == null) { throw new Exception("ftp连接失败!FTP信息:" + ftpVo.toString()); } File localFile = new File(localDir + localFileName); // 判断文件在本地是否存在 if (localFile != null && localFile.exists() && ftpVo.isDelOldFile()) { localFile.delete(); } CoFile tmpfile = new LocalFile(localDir + localFileName); // 本地文件 CoFile ftpFile = new FtpFile(ftpDir + ftpFileName, ftp); // 远程文件名 // 下载文件 if (!CoLoad.copy(tmpfile, ftpFile)) {// 下载 message = ftpFileName + "下载失败:" + ftpVo.toString(); logger.error("文件下载失败:" + ftpVo.toString()); } else {// 下载成功 message = ftpFileName + "下载成功:" + ftpVo.toString(); logger.info("文件下载成功:" + ftpVo.toString()); } } catch (Exception e) { message = ftpFileName + "下载失败:" + e.getMessage(); logger.error(e.getMessage(), e); } finally { ftp.disconnect(); } return message; } }
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); } }
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"); } } }