建立一个ftpbean管理ftp的ip,端口号,用户名,密码信息
建立一个FtpManager 操作ftp的上传,删除的功能的封装
建立一个FtpService 得到ftpbean,调用FtpManager方法实现需求
建立一个封装文件的对象FileList
ftpbean
/**
* FTP服务器信息类 * @author * 2010-8-11 上午09:56:28 */public class FtpInfoBean { /** * 版本控制用 */ public final static String VER = "2010-08-17 10:58"; /** * 类标题 */ public final static String CLASS_TITLE = "FTP服务器信息类"; protected String ip = null; //服务器地址 protected int port = 21; //服务器端口 protected String userName = null; //登录用户名 protected String pwd = null; //登录密码 protected String path = null; //默认路径 protected boolean pasvMode = false; //是否被动链接 /** * 构造函数 * @author */ public FtpInfoBean() { super(); } /** * 是否被动链接 * * 2010-8-11 上午10:05:18 * @return 是否被动链接 */ public boolean isPasvMode() { return pasvMode; } /** * 设置是否被动链接 * * 2010-8-11 上午10:04:58 * @param pasvMode 是否被动链接 */ public void setPasvMode(boolean pasvMode) { this.pasvMode = pasvMode; } /** * 获取默认路径 * 2010-8-11 上午10:04:25 * @return 默认路径 */ public String getPath() { if(path==null) { path = ""; } return path; } /** * 设置默认路径 * * 2010-8-11 上午10:03:58 * @param path 默认路径 */ public void setPath(String path) { this.path = path; } /** * 获取登录密码 * * 2010-8-11 上午10:03:35 * @return 登录密码 */ public String getPwd() { if(pwd==null) { pwd = ""; } return pwd; } /** * 设置登录密码 * * 2010-8-11 上午10:03:12 * @param pwd 登录密码 */ public void setPwd(String pwd) { this.pwd = pwd; } /** * 获取登录名 * * 2010-8-11 上午10:02:43 * @return 登录名 */ public String getUserName() { if(userName==null) { userName = ""; } return userName; } /** * 设置登录名 * * 2010-8-11 上午10:02:13 * @param userName 登录名 */ public void setUserName(String userName) { this.userName = userName; } /** * 获取服务器端口 * * 2010-8-11 上午10:01:33 * @return 服务器端口 */ public int getPort() { return port; } /** * 设置服务器端口 * * 2010-8-11 上午10:01:09 * @param port 服务器端口 */ public void setPort(int port) { if(port<1) { return; } this.port = port; } /** * 获取服务器地址 * * 2010-8-11 上午10:00:48 * @return 服务器地址 */ public String getIP() { if(ip==null) { ip = ""; } return ip; } /** * 设置服务器地址 * * 2010-8-11 上午10:00:27 * @param ip 服务器地址 */ public void setIP(String ip) { this.ip = ip; }}FtpManager
/**
* FTP功能管理类 * @author * 2010-8-16 上午09:47:51 */public class FtpManager { /** * 版本控制用 */ public final static String VER = "2010-08-24 15:38"; /** * 类标题 */ public final static String CLASS_TITLE = "FTP功能管理类"; protected Log logger = LogFactory.getLog(getClass()); protected ArrayList<FtpInfoBean> ftpInfoBeanList = null; //FTP服务器信息序列 /** * 构造函数 * @author */ public FtpManager() { super(); } /** * 获取有效的FTP信息 * 2010-8-11 上午10:08:13 * @return 有效的FTP信息序列 */ protected ArrayList<FtpInfoBean> getFtpInfoBeanList() { if(ftpInfoBeanList==null) { ftpInfoBeanList = new ArrayList<FtpInfoBean>(); } return ftpInfoBeanList; } /** * 获取FTP信息数 * * 2010-8-11 上午10:08:32 * @return FTP信息数 */ public int getFtpInfoSize() { return getFtpInfoBeanList().size(); } /** * 清除所有FTP信息 * * 2010-8-11 上午10:10:37 */ public void clearFtpInfo() { ftpInfoBeanList = null; } /** * 添加FTP服务器信息 * * 2010-8-11 上午10:11:59 * @param ip 服务器地址 * @param port 服务器端口 * @param uName 登录用户名 * @param pwd 登录密码 * @param path FTP根路径 * @param pasv 是否为Pasv模式 */ public void addFtpInfo( String ip ,int port ,String uName ,String pwd ,String path ,boolean pasv) { //构建新的FTP服务器信息类 FtpInfoBean fib = new FtpInfoBean(); fib.setIP(ip); fib.setPort(port); fib.setUserName(uName); fib.setPwd(pwd); fib.setPath(path); fib.setPasvMode(pasv); getFtpInfoBeanList().add(fib); } /** * 打开FTP服务器 * * 2010-8-11 上午10:33:32 * @param fib FTP服务器信息类 * @return FTP客户端 * @throws Exception 执行发生异常 */ protected FTPClient openServer(FtpInfoBean fib) throws Exception { FTPClient ftpClient = null; //FTP客户端 try { ftpClient = new FTPClient(); logger.info("Begin Open Ftp Server:["+fib.getIP()+"]["+fib.getPort()+"]"); //打开连接 ftpClient.connect(fib.getIP(),fib.getPort()); logger.info("Open Ftp Server Completed:["+fib.getIP()+"]["+fib.getPort()+"]"); }catch(Exception e) { e.printStackTrace(); logger.error("Open Ftp Server Exception:["+fib.getIP()+"]["+fib.getPort()+"] E:["+e+"]",e); throw new Exception(e); } try { logger.info("Begin Login Ftp Server:["+fib.getUserName()+"]"); //执行登录 ftpClient.login(fib.getUserName(),fib.getPwd()); logger.info("Login Ftp Server Completed:["+fib.getUserName()+"]"); ftpClient.setPassive(fib.isPasvMode()); }catch(Exception e) { e.printStackTrace(); logger.error("Login Ftp Server Exception:["+fib.getUserName()+"]["+fib.getPwd()+"] E:["+e+"]",e); throw new Exception(e); } return ftpClient; } /** * 进入路径 * @author * 2008-1-14下午12:42:15 * @param ftpClient ftp客户端 * @param path 指定路径 * @throws Exception 执行发生异常 */ public void cdPath(FTPClient ftpClient,String path) throws Exception { //整理FTP路径 path = swapString(path,"\\","/"); path = swapString(path,"///","/"); path = swapString(path,"//","/"); logger.info("Begin CD Path:["+path+"]"); try { if (path.length()>0) { try { ftpClient.changeDirectory("/"); //先回到根路径 }catch(Exception e2) {} ftpClient.changeDirectory(path); //进入指定文件夹 } }catch(Exception e) { try { ftpClient.changeDirectory("/"); //先回到根路径 }catch(Exception e3) {} mkDir(ftpClient,path.split("/"),0); //逐级创建并进入文件夹 } } /** * 逐级创建并进入文件夹 * * 2010-8-17 上午10:08:47 * @param ftpClient ftp客户端 * @param pathSubs 文件夹数组 * @param index 子文件夹索引指针 */ protected void mkDir(FTPClient ftpClient,String[] pathSubs,int index) { if(pathSubs[index]!=null && pathSubs[index].trim().length()>0) { try { ftpClient.changeDirectory(pathSubs[index]); //进入指定文件夹 }catch(Exception e) { try { //尝试建立文件夹 ftpClient.createDirectory(pathSubs[index]); }catch(Exception e4) {} try { ftpClient.changeDirectory(pathSubs[index]); //进入指定文件夹 }catch(Exception e2) {} } } index++; if(index<pathSubs.length) { mkDir(ftpClient,pathSubs,index); } } /** * 将本地文件通过ftp传送到目标服务器中 * * 2010-8-11 上午10:19:14 * @param localFilePath 本地文件全路径 * @param ftpFilePath 目标ftp服务器相对路径 * @param ftpFileName 目标文件名 * @throws Exception 执行发生异常 */ public void transfer( String localFilePath ,String ftpFilePath ,String ftpFileName) throws Exception { if(localFilePath==null || localFilePath.length()<1) { return; } if(ftpFilePath==null) { ftpFilePath = ""; }else { ftpFilePath = swapString(ftpFilePath,"\\","/"); if(ftpFilePath.startsWith("/")) { ftpFilePath = ftpFilePath.substring(1,ftpFilePath.length()); } } if(ftpFileName==null || ftpFileName.length()<1) { ftpFileName = getFileName(localFilePath); } FTPClient ftpClient = null; //FTP客户端 String ftpPath = null; //FTP目标路径 StringBuffer exceptionSbf = new StringBuffer(); //异常信息 for(int i=0;i<getFtpInfoSize();i++) { //获取ftp服务器信息元素 FtpInfoBean fib = getFtpInfoBeanList().get(i); if(fib==null) { continue; } try { ftpClient = openServer(fib); //打开服务器 logger.info("Begin Transfer Ftp File:[" +localFilePath+"]["+ftpFilePath+"]"); //整理上传路径 ftpPath = swapString(fib.getPath(),"\\","/"); if(!ftpPath.endsWith("/")) { ftpPath += "/"; } ftpPath += ftpFilePath; //进入指定路径 cdPath(ftpClient,ftpPath); try { ftpClient.setType(FTPClient.TYPE_BINARY); //修改传送模式 }catch(Exception e2) {} //执行上传 ftpClient.upload( ftpFileName,new FileInputStream(new File(localFilePath)),0,0,null); }catch(Exception e) { e.printStackTrace(); exceptionSbf.append(e).append("\n"); }finally { if(ftpClient!=null) { try { ftpClient.logout(); ftpClient.disconnect(true); }catch(Exception e) {} ftpClient = null; } } } if(exceptionSbf.length()>0) { logger.error(exceptionSbf.toString()); throw new Exception(exceptionSbf.toString()); } } /** * 删除指定路径中的内容 * * 2010-8-17 上午11:17:20 * @param ftpFilePath ftp相对路径 * @param deleteSelf 是否在删除内容后也删除当前文件夹 */ public void deletePath(String ftpFilePath,boolean deleteSelf) { if(ftpFilePath==null || ftpFilePath.length()<1) { return; }else { ftpFilePath = swapString(ftpFilePath,"\\","/"); if(ftpFilePath.startsWith("/")) { ftpFilePath = ftpFilePath.substring(1,ftpFilePath.length()); } } logger.info("Begin Delete Ftp Path:["+ftpFilePath+"]"); FTPClient ftpClient = null; //ftp客户端 String ftpPath = null; //整理后的目标路径 for(int i=0;i<getFtpInfoSize();i++) { //获取ftp服务器信息元素 FtpInfoBean fib = getFtpInfoBeanList().get(i); if(fib==null) { continue; } try { ftpClient = openServer(fib); //打开服务器 //整理目标路径 ftpPath = swapString(fib.getPath(),"\\","/"); if(!ftpPath.endsWith("/")) { ftpPath += "/"; } ftpPath += ftpFilePath; //执行删除路径 doDeletePath(ftpClient,ftpPath,deleteSelf); }catch(Exception e) { //e.printStackTrace(); }finally { if(ftpClient!=null) { try { ftpClient.logout(); ftpClient.disconnect(true); }catch(Exception e) {} ftpClient = null; } } } } /** * 删除指定服务器路径 * * 2010-8-17 上午11:15:59 * @param ftpClient ftp客户端 * @param ftpFilePath 服务器路径 * @param deleteSelf 是否在删除内容后也删除当前文件夹 * @throws Exception 执行发生异常 */ protected void doDeletePath( FTPClient ftpClient,String ftpFilePath,boolean deleteSelf) throws Exception { try { ftpClient.changeDirectory(ftpFilePath); }catch(Exception e) {} //获取信息数组 FTPFile[] infos = ftpClient.list(); if(infos!=null) { for(int i=0;i<infos.length;i++) { if(infos[i]==null) { continue; } if(infos[i].getType()==FTPFile.TYPE_DIRECTORY) { //目录 doDeletePath(ftpClient,ftpFilePath+"/"+infos[i].getName(),true); }else { //文件或其它 ftpClient.deleteFile(infos[i].getName()); } } } if(deleteSelf) { try { ftpClient.changeDirectoryUp(); }catch(Exception e) {} try { ftpClient.deleteDirectory(ftpFilePath); }catch(Exception e) {} } } /** * 删除FTP服务器端的文件 * * 2010-8-11 上午11:02:35 * @param ftpFilePath 服务器相对路径(相对于FTP服务器设置的根路径) * @param ftpName 服务器文件 */ public void deleteFile(String ftpFilePath,String ftpName) { if(ftpFilePath==null || ftpFilePath.length()<1) { ftpFilePath = ""; }else { ftpFilePath = swapString(ftpFilePath,"\\","/"); if(ftpFilePath.startsWith("/")) { ftpFilePath = ftpFilePath.substring(1,ftpFilePath.length()); } } if(ftpName==null || ftpName.length()<1) { //如果文件名为空,则从文件路径中获取文件名 ftpName = getFileName(ftpFilePath); ftpFilePath = ftpFilePath.substring(0,ftpFilePath.lastIndexOf("/")); } logger.info("Begin Delete Ftp File:["+ftpFilePath+"]"); FTPClient ftpClient = null; //ftp客户端 String ftpPath = null; //整理后的目标路径 for(int i=0;i<getFtpInfoSize();i++) { //获取ftp服务器信息元素 FtpInfoBean fib = getFtpInfoBeanList().get(i); if(fib==null) { continue; } try { ftpClient = openServer(fib); //打开服务器 //整理目标路径 ftpPath = swapString(fib.getPath(),"\\","/"); if(!ftpPath.endsWith("/")) { ftpPath += "/"; } ftpPath += ftpFilePath; //进入指定路径 cdPath(ftpClient,ftpPath); //执行删除(删除文件不抛异常,因为可能文件不存在) try { ftpClient.deleteFile(ftpName); }catch(Exception ee) {} }catch(Exception e) { //e.printStackTrace(); }finally { if(ftpClient!=null) { try { ftpClient.logout(); ftpClient.disconnect(true); }catch(Exception e) {} ftpClient = null; } } } } /** * 批量将本地文件通过ftp传送到目标服务器中 * * 2010-8-11 上午10:17:09 * @param localFileList 本地文件序列(文件全路径) * @param targetFileList ftp目标路径(相对路径) * @param targetFileNameList ftp目标文件名 * @throws Exception 执行发生异常 */ public void transfers( List<String> localFileList ,List<String> targetFileList ,List<String> targetFileNameList) throws Exception { if(localFileList==null || targetFileList==null) { return; } int size; //序列大小 if(localFileList.size()>targetFileList.size()) { size = targetFileList.size(); }else { size = localFileList.size(); } //异常信息 StringBuffer exceptionSbf = new StringBuffer(); for(int i=0;i<size;i++) { try { if(targetFileNameList==null || targetFileNameList.size()<i) { transfer(localFileList.get(i),targetFileList.get(i),null); }else { transfer( localFileList.get(i) ,targetFileList.get(i) ,targetFileNameList.get(i)); } }catch(Exception e) { e.printStackTrace(); exceptionSbf.append(e).append("\n"); } } if(exceptionSbf.length()>0) { logger.error(exceptionSbf.toString()); throw new Exception(exceptionSbf.toString()); } } /** * 替换字符串中指定的字符 * @author * @param strString 要操作的字符串 * @param strSub 需要替换的字符串 * @param strTo 替换成的字符串 * @return 替换后的字符串 * 2006-1-5 10:10:04 */ protected String swapString(String str,String fromStr,String toStr) { //导入参数合法化 if (str==null) { return null; } String[] strs = split(str,fromStr); StringBuffer reStr = new StringBuffer(); if (strs!=null && strs.length>0) { for (int i=0;i<strs.length;i++) { reStr.append(strs[i]); if (i<strs.length-1) { reStr.append(toStr); } } } return reStr.toString(); } /** * 将字符串按照指定字符分割为字符串数组 * @author * 2006-10-26下午11:54:09 * @param source 原字符串 * @param splitStr 指定分割字符 * @return 分割后的字符串数组 */ protected String[] split(String source,String splitStr) { //获取分割后的序列 ArrayList<String> reArrl = splitToList(source,splitStr); //构件返回值 String[] reStrs = new String[reArrl.size()]; //复制值 reArrl.toArray(reStrs); return reStrs; } /** * 从字符串序列转换为序列 * @author * 2007-5-30下午08:31:55 * @param source 源字符串 * @param point 分割符 * @return 转换后的序列 */ protected ArrayList<String> splitToList(String source,String point) { if (source==null || source.length()==0) { return new ArrayList<String>(); } //构造返回容器 ArrayList<String> reArrl = new ArrayList<String>(); while(true) { //获取分割点 int splitPoint = source.indexOf(point); if (splitPoint<0) { reArrl.add(source); break; } reArrl.add(source.substring(0,splitPoint)); //构造分割后的字符串 source = source.substring(splitPoint+point.length(),source.length()); } return reArrl; } /** * 从文件路径中获得文件名 * @author * @param filePathStr 文件全路径 * @return 文件名 * 2006-4-1 14:30:55 */ protected String getFileName(String filePathStr) { if(filePathStr==null || filePathStr.length()<1) { return ""; } //获取分隔符 int point1 = filePathStr.lastIndexOf("/"); int point2 = filePathStr.lastIndexOf("\\"); if(point1>point2) { return filePathStr.substring(point1+1,filePathStr.length()); }else if(point1<point2) { return filePathStr.substring(point2+1,filePathStr.length()); } //point1==point2 这种情况只有 都为-1时 return filePathStr; }}FtpServiceImpl 接口省略了
/**
* FTP服务类 (该类需要常驻内存) * FtpServiceImpl * @author * 2010-8-11 上午09:55:06 */@SuppressWarnings("unchecked")@Service("ftpService")@Transactionalpublic class FtpServiceImpl extends GenericBaseCommonDao implements FtpService { /** * 版本控制用 */ public final static String VER = "2010-08-17 14:44"; /** * 类标题 */ public final static String CLASS_TITLE = "FTP服务类"; /** * 构造函数 * @author */ public FtpServiceImpl() { super(); } /** * 删除指定路径中的内容 * * 2010-8-17 上午11:17:20 * @param type 服务器类型 * @param ftpFilePath ftp相对路径 * @param deleteSelf 是否在删除内容后也删除当前文件夹 * @throws Exception 执行发生异常 */ public void deletePath( String type,String ftpFilePath,boolean deleteSelf) throws Exception { //获取服务器管理类 FtpManager fm = getFtpManagerByType(type); if(fm==null) { return; } fm.deletePath(ftpFilePath,deleteSelf); } /** * 通过ftp服务器类型获取服务器管理类 * * 2010-8-16 上午10:15:33 * @param type ftp服务器类型 * @return 服务器管理类 * @throws Exception 执行发生异常 */ protected FtpManager getFtpManagerByType(String type) throws Exception { String sql="select " + "SERVERNAME, " + "SERVERIP," + "PORT," + "USERNAME," + "PASSWORD," + "PATH," + "SERVERSTATUS,"+ "SERVERTYPE," + "ACCESSTYPE " + " from tb_sys_server "+ "where deleted = 0 and SERVERTYPE="+type; // List<SysServer> rs = new ArrayList<SysServer> (); Query query = getSession().createSQLQuery(sql); Iterator iter = query.list().iterator(); SysServer s=null; if(query.list().iterator().hasNext()){ Object[] obj = (Object[])iter.next(); String servername = (String)obj[0]; String serverip = (String)obj[1]; int port = (Integer)obj[2]; String username = (String)obj[3]; String passwd = (String)obj[4]; String path = (String)obj[5]; String serverstatus= (String)obj[6]; String servertype = (String)obj[7]; String accesstype = (String)obj[8]; s = new SysServer(servername,serverip,username,passwd,path,serverstatus,servertype,accesstype,port); // rs.add(s); } /*if(rs==null || rs.size()<1) { return null; }*/ //构建ftp服务管理类 FtpManager fm = new FtpManager(); /*for(int i=0;i<rs.size();i++) { //获取记录集元素 SysServer ss = rs.get(i); if(ss==null) { continue; } fm.addFtpInfo( ss.getServerip() ,ss.getPort() ,ss.getUsername() ,ss.getPasswd() ,ss.getPath() ,(ss.getAccesstype()!=null && ss.getAccesstype().equals("1"))?true:false); }*/ fm.addFtpInfo( s.getServerip() ,s.getPort() ,s.getUsername() ,s.getPasswd() ,s.getPath() ,(s.getAccesstype()!=null && s.getAccesstype().equals("1"))?true:false); return fm; } /** * 覆盖方法 * 2010-8-16 上午10:00:42 */ public void deleteFile( String type ,String ftpFilePath ,String ftpFileName) throws Exception { //获取服务器管理类 FtpManager fm = getFtpManagerByType(type); if(fm==null) { return; } fm.deleteFile(ftpFilePath,ftpFileName); } /** * 覆盖方法 * * 2010-8-16 上午10:00:45 */ public void transfer( String type ,String localFilePath ,String ftpFilePath ,String ftpFileName) throws Exception { //获取服务器管理类 FtpManager fm = getFtpManagerByType(type); if(fm==null) { return; } fm.transfer(localFilePath,ftpFilePath,ftpFileName); } /** * 覆盖方法 * * 2010-8-16 上午10:00:48 */ public void transfers( String type ,List<String> localFileList ,List<String> targetFileList ,List<String> targatFileName) throws Exception { //获取服务器管理类 FtpManager fm = getFtpManagerByType(type); if(fm==null) { return; } fm.transfers(localFileList,targetFileList,targatFileName); }}FileList
/**
* ftp文件同步类 * @author shijx * 2010-8-17 */public class FileList{ private List<String> localFile=new ArrayList<String>();//本地文件全路径序列 private List<String> ftpFileFoldList = new ArrayList<String>(); //目标文件相对路径序列 private List<String> ftpFileNameList = new ArrayList<String>(); //目标文件名序列 public FileList() { } public FileList(List<String> localFile,List<String> ftpFileFoldList,List<String> ftpFileNameList) { this.setFtpFileFoldList(ftpFileFoldList); this.setLocalFile(localFile); this.setFtpFileNameList(ftpFileNameList); } public List<String> getLocalFile() { return localFile; } public void setLocalFile(List<String> localFile) { this.localFile = localFile; } public List<String> getFtpFileFoldList() { return ftpFileFoldList; } public void setFtpFileFoldList(List<String> ftpFileFoldList) { this.ftpFileFoldList = ftpFileFoldList; } public List<String> getFtpFileNameList() { return ftpFileNameList; } public void setFtpFileNameList(List<String> ftpFileNameList) { this.ftpFileNameList = ftpFileNameList; }}需要ftp4j-1.5.1.jar