封裝了個FTP 處理類,實現異構系統的交互,主要用了commons net jar包,實現服務器之間的文件上傳、刪除、下載、建立目錄等功能。 java
package com.conmon.msgsync; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.net.ftp.FTPClient; //import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger; /** * 遠程FTP處理類 * @author SU * @version 1.0, 2012/09/15 */ public class FTPUtil { private Logger logger = Logger.getLogger(FTPUtil.class); private String ip ; private int port; private String pwd; private String user; private FTPClient ftpClient; private FTPUtil() { } public FTPUtil(String ip, int port, String user, String pwd) { this.ip = ip; this.port = port; this.user = user; this.pwd = pwd; } /** * 鏈接遠程FTP服務器 * @param ip ip地址 * @param port 端口號 * @param user 用戶名 * @param pwd 密碼 * @return * @throws Exception */ public boolean connectServer(String ip, int port, String user, String pwd) throws Exception { boolean isSuccess = false; try { ftpClient = new FTPClient(); ftpClient.connect(ip, port); ftpClient.setControlEncoding("GBK"); // FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); //此類commons-net-2.0不提供 // conf.setServerLanguageCode("zh"); ftpClient.login(user, pwd); ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { isSuccess = true; System.out.println("--鏈接ftp服務器成功!!!"); } else { ftpClient.disconnect(); logger.error("連不上ftp服務器!"); // throw new BossOperException(); } } catch (Exception e) { logger.error("鏈接FTP服務器異常..", e); e.printStackTrace(); } return isSuccess; } /** * 遠程FTP上傳文件 * @param remotePath * @param localPath * @param files * @return * @throws Exception */ public File uploadFile(String remotePath, List<File> files)throws Exception { File fileIn = null; OutputStream os = null; FileInputStream is = null; try { for (File file : files) { if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) { System.out.println("----進入文件上傳到FTP服務器--->"); ftpClient.changeWorkingDirectory(remotePath); os = ftpClient.storeFileStream(file.getName()); fileIn = file; is = new FileInputStream(fileIn); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } } } } catch (Exception e) { logger.error("上傳FTP文件異常: ", e); } finally { os.close(); is.close(); ftpClient.logout(); if (ftpClient.isConnected()) { ftpClient.disconnect(); } } return fileIn; } /** * 遠程FTP上刪除一個文件 * @param remotefilename * @return */ public boolean deleteFile(String remotefilename) { boolean flag = true; try { if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) { flag = ftpClient.deleteFile(remotefilename); if (flag) { System.out.println("遠程刪除FTP文件成功!"); } else { System.out.println("-----遠程刪除FTP文件失敗!----"); } } } catch (Exception ex) { logger.error("遠程刪除FTP文件異常: ", ex); ex.printStackTrace(); } return flag; } /** * 遠程FTP刪除目錄下的全部文件 * @param remotePath * @param localPath * @return * @throws Exception */ public void deleteAllFile(String remotePath, String localPath) throws Exception { try { if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) { ftpClient.changeWorkingDirectory(remotePath); FTPFile[] ftpFiles = ftpClient.listFiles(); for (FTPFile file : ftpFiles) { ftpClient.deleteFile(file.getName()); } } } catch (Exception e) { logger.error("從FTP服務器刪除文件異常:", e); e.printStackTrace(); } finally { ftpClient.logout(); if (ftpClient.isConnected()) { ftpClient.disconnect(); } } } /** * 遠程FTP上建立目錄 * @param dir * @return */ public boolean makeDirectory(String dir) { boolean flag = true; try { if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) { flag = ftpClient.makeDirectory(dir); if (flag) { System.out.println("make Directory " + dir + " succeed"); } else { System.out.println("make Directory " + dir + " false"); } } } catch (Exception ex) { logger.error("遠程FTP生成目錄異常:", ex); ex.printStackTrace(); } return flag; } /** * 遠程FTP下載文件 * * @param remotePath * @param localPath * @return * @throws Exception */ public List<File> downloadFile(String remotePath, String localPath ) throws Exception { List<File> result = new ArrayList<File>(); File fileOut = null; InputStream is = null; FileOutputStream os = null; try { if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) { ftpClient.changeWorkingDirectory(remotePath); FTPFile[] ftpFiles = ftpClient.listFiles(); for (FTPFile file : ftpFiles) { is = ftpClient.retrieveFileStream(file.getName()); if (localPath != null && !localPath.endsWith(File.separator)) { localPath = localPath + File.separator; File path = new File(localPath); if (!path.exists()) { path.mkdirs(); } } fileOut = new File(localPath + file.getName()); os = new FileOutputStream(fileOut); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } result.add(fileOut); ftpClient.completePendingCommand(); os.flush(); is.close(); os.close(); } for (FTPFile file : ftpFiles) { ftpClient.deleteFile(file.getName()); } } } catch (Exception e) { logger.error("從FTP服務器下載文件異常:", e); e.printStackTrace(); } finally { ftpClient.logout(); if (ftpClient.isConnected()) { ftpClient.disconnect(); } } return result; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } /** * 測試方法 * @param args */ public static void main(String[] args) { String ip = "10.123.148.88"; int port = 21 ; String user ="root"; String pwd ="root" ; String remotePath = "//home//V010//01//000011//" ; //上傳文件配置 // List<File> fileList = new ArrayList<File>(); //// File onefile = new File("F:\\V010\\01\\000011\\RSP\\0100001120120701122712_Day.txt"); // File onefile = new File("F:\\V010\\01\\000011\\RSP\\" ,"01000011201209263112839_Day.txt"); // System.out.println("----本地文件路徑--->"+ onefile.getAbsolutePath()); // fileList.add(onefile); FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd); try { // ftpupload.uploadFile(remotePath, fileList); //測試上傳文件 //刪除文件 // String remotefilename = remotePath+"01000011201209263112839_Day.txt"; // System.out.println("----遠程FTF上的文件名----"+remotefilename); // ftpupload.deleteFile(remotefilename); //下載目錄下全部的文件 String localPath = "F:\\TEST\\" ; // ftpupload.downloadFile(remotePath, localPath); ftpupload.deleteAllFile(remotePath, localPath); } catch (Exception e) { e.printStackTrace(); } } }