org.apache.commons.net.ftp.FTPClient
阿新 • • 發佈:2018-11-10
package com.util;
import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
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;
public class FTPClientTest {
private static final Log logger = LogFactory.getLog(FTPClientTest.class); private String userName; //FTP 登入使用者名稱 private String password; //FTP 登入密碼 private String ip; //FTP 伺服器地址IP地址 private int port; //FTP 埠 private Properties property = null; //屬性集 private String configFile = "conf/application.properties"; //配置檔案的路徑名 private FTPClient ftpClient = null; //FTP 客戶端代理 //時間格式化 private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm"); //FTP狀態碼 public int i = 1; /** * 連線到伺服器 * * @return true 連線伺服器成功,false 連線伺服器失敗 */ public boolean connectServer() { boolean flag = true; if (ftpClient == null) { int reply; try { if(setArg(configFile)){ ftpClient = new FTPClient(); ftpClient.setControlEncoding("GBK"); //ftpClient.configure(getFtpConfig()); ftpClient.connect(ip,port); ftpClient.login(userName, password); reply = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); logger.debug("FTP 服務拒絕連線!"); flag = false; } i++; }else{ flag = false; } } catch (SocketException e) { flag = false; e.printStackTrace(); logger.debug("登入ftp伺服器 " + ip + " 失敗,連線超時!"); } catch (IOException e) { flag = false; e.printStackTrace(); logger.debug("登入ftp伺服器 " + ip + " 失敗,FTP伺服器無法開啟!"); } } return flag; } /** * 上傳檔案 * * @param remoteFile * 遠端檔案路徑,支援多級目錄巢狀 * @param localFile * 本地檔名稱,絕對路徑 * */ public boolean uploadFile(String remoteFile, File localFile) throws IOException { boolean flag = false; InputStream in = new FileInputStream(localFile); String remote = new String(remoteFile.getBytes("GBK"),"iso-8859-1"); if(ftpClient.storeFile(remote, in)){ flag = true; logger.debug(localFile.getAbsolutePath()+"上傳檔案成功!"); }else{ logger.debug(localFile.getAbsolutePath()+"上傳檔案失敗!"); } in.close(); return flag; } /** * 上傳單個檔案,並重命名 * * @param localFile--本地檔案路徑 * @param localRootFile--本地檔案父資料夾路徑 * @param distFolder--新的檔名,可以命名為空"" * @return true 上傳成功,false 上傳失敗 * @throws IOException */ public boolean uploadFile(String local, String remote) throws IOException { boolean flag = true; String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); // 建立伺服器遠端目錄結構,建立失敗直接返回 if (!CreateDirecroty(remote)) { return false; } } FTPFile[] files = ftpClient.listFiles(new String(remoteFileName)); File f = new File(local); if(!uploadFile(remoteFileName, f)){ flag = false; } return flag; } /** * 上傳資料夾內的所有檔案 * * * @param filename * 本地資料夾絕對路徑 * @param uploadpath * 上傳到FTP的路徑,形式為/或/dir1/dir2/../ * @return true 上傳成功,false 上傳失敗 * @throws IOException */ public List uploadManyFile(String filename, String uploadpath) { boolean flag = true; List l = new ArrayList(); StringBuffer strBuf = new StringBuffer(); int n = 0; //上傳失敗的檔案個數 int m = 0; //上傳成功的檔案個數 try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.changeWorkingDirectory("/"); File file = new File(filename); File fileList[] = file.listFiles(); for (File upfile : fileList) { if (upfile.isDirectory()) { uploadManyFile(upfile.getAbsoluteFile().toString(),uploadpath); } else { String local = upfile.getCanonicalPath().replaceAll("\\\\","/"); String remote = uploadpath.replaceAll("\\\\","/") + local.substring(local.indexOf("/") + 1); flag = uploadFile(local, remote); ftpClient.changeWorkingDirectory("/"); } if (!flag) { n++; strBuf.append(upfile.getName() + ","); logger.debug("檔案[" + upfile.getName() + "]上傳失敗"); } else{ m++; } } l.add(0, n); l.add(1, m); l.add(2, strBuf.toString()); } catch (NullPointerException e) { e.printStackTrace(); logger.debug("本地檔案上傳失敗!找不到上傳檔案!", e); } catch (Exception e) { e.printStackTrace(); logger.debug("本地檔案上傳失敗!", e); } return l; } /** * 下載檔案 * * @param remoteFileName --伺服器上的檔名 * @param localFileName--本地檔名 * @return true 下載成功,false 下載失敗 */ public boolean loadFile(String remoteFileName, String localFileName) { boolean flag = true; // 下載檔案 BufferedOutputStream buffOut = null; try { buffOut = new BufferedOutputStream(new FileOutputStream(localFileName)); flag = ftpClient.retrieveFile(remoteFileName, buffOut); } catch (Exception e) { e.printStackTrace(); logger.debug("本地檔案下載失敗!", e); } finally { try { if (buffOut != null) buffOut.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } /** * 刪除一個檔案 */ public boolean deleteFile(String filename) { boolean flag = true; try { flag = ftpClient.deleteFile(filename); if (flag) { logger.debug("刪除檔案"+filename+"成功!"); } else { logger.debug("刪除檔案"+filename+"成功!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 刪除目錄 */ public void deleteDirectory(String pathname) { try { File file = new File(pathname); if (file.isDirectory()) { File file2[] = file.listFiles(); } else { deleteFile(pathname); } ftpClient.removeDirectory(pathname); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 刪除空目錄 */ public void deleteEmptyDirectory(String pathname) { try { ftpClient.removeDirectory(pathname); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 列出伺服器上檔案和目錄 * * @param regStr --匹配的正則表示式 */ public void listRemoteFiles(String regStr) { try { String files[] = ftpClient.listNames(regStr); if (files == null || files.length == 0) logger.debug("沒有任何檔案!"); else { for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } } } catch (Exception e) { e.printStackTrace(); } } /** * 列出Ftp伺服器上的所有檔案和目錄 */ public void listRemoteAllFiles() { try { String[] names = ftpClient.listNames(); for (int i = 0; i < names.length; i++) { System.out.println(names[i]); } } catch (Exception e) { e.printStackTrace(); } } /** * 關閉連線 */ public void closeConnect() { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } /** * 設定傳輸檔案的型別[文字檔案或者二進位制檔案] * * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE * */ public void setFileType(int fileType) { try { ftpClient.setFileType(fileType); } catch (Exception e) { e.printStackTrace(); } } /** * 設定引數 * * @param configFile --引數的配置檔案 */ private boolean setArg(String configFile) { boolean flag = true; property = new Properties(); BufferedInputStream inBuff = null; try { inBuff = new BufferedInputStream(new FileInputStream(getClass().getResource("/").getPath() + configFile)); property.load(inBuff); userName = property.getProperty("username"); password = property.getProperty("password"); ip = property.getProperty("ip"); port = Integer.parseInt(property.getProperty("port")); } catch (FileNotFoundException e1) { flag = false; logger.debug("配置檔案 " + configFile + " 不存在!"); } catch (IOException e) { flag = false; logger.debug("配置檔案 " + configFile + " 無法讀取!"); } return flag; } /** * 進入到伺服器的某個目錄下 * * @param directory */ public boolean changeWorkingDirectory(String directory) { boolean flag = true; try { flag = ftpClient.changeWorkingDirectory(directory); if (flag) { logger.debug("進入資料夾"+ directory + " 成功!"); } else { logger.debug("進入資料夾"+ directory + " 失敗!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 返回到上一層目錄 */ public void changeToParentDirectory() { try { ftpClient.changeToParentDirectory(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 重新命名檔案 * * @param oldFileName --原檔名 * @param newFileName --新檔名 */ public void renameFile(String oldFileName, String newFileName) { try { ftpClient.rename(oldFileName, newFileName); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 設定FTP客服端的配置--一般可以不設定 * * @return ftpConfig */ private FTPClientConfig getFtpConfig() { FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); return ftpConfig; } /** * 轉碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉碼 * * @param obj * @return "" */ private String iso8859togbk(Object obj) { try { if (obj == null) return ""; else return new String(obj.toString().getBytes("iso-8859-1"), "GBK"); } catch (Exception e) { return ""; } } /** * 在伺服器上建立一個資料夾 * * @param dir 資料夾名稱,不能含有特殊字元,如 \ 、/ 、: 、* 、?、 "、 <、>... */ public boolean makeDirectory(String dir) { boolean flag = true; try { flag = ftpClient.makeDirectory(dir); if (flag) { logger.debug("建立資料夾"+ dir + " 成功!"); } else { logger.debug("建立資料夾"+ dir + " 失敗!"); } } catch (Exception e) { e.printStackTrace(); } return flag; } // 檢查路徑是否存在,存在返回true,否則false public boolean existFile(String path) throws IOException { boolean flag = false; FTPFile[] ftpFileArr = ftpClient.listFiles(path); /* for (FTPFile ftpFile : ftpFileArr) { if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path)) { flag = true; break; } } */ if(ftpFileArr.length > 0){ flag = true; } return flag; } /** * 遞迴建立遠端伺服器目錄 * * @param remote * 遠端伺服器檔案絕對路徑 * * @return 目錄建立是否成功 * @throws IOException */ public boolean CreateDirecroty(String remote) throws IOException { boolean success = true; String directory = remote.substring(0, remote.lastIndexOf("/") + 1); // 如果遠端目錄不存在,則遞迴建立遠端伺服器目錄 if (!directory.equalsIgnoreCase("/")&& !changeWorkingDirectory(new String(directory))) { int start = 0; int end = 0; if (directory.startsWith("/")) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory = new String(remote.substring(start, end).getBytes("GBK"),"iso-8859-1"); if (changeWorkingDirectory(subDirectory)) { if (makeDirectory(subDirectory)) { changeWorkingDirectory(subDirectory); } else { logger.debug("建立目錄["+subDirectory+"]失敗"); System.out.println("建立目錄["+subDirectory+"]失敗"); success = false; return success; } } start = end + 1; end = directory.indexOf("/", start); // 檢查所有目錄是否建立完畢 if (end <= start) { break; } } } return success; } public static void main(String[] args) { FTPClientTest ftpClient = new FTPClientTest(); if(ftpClient.connectServer()){ ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 設定傳輸二進位制檔案 ftpClient.uploadManyFile("H:\\d", "/d/"); ftpClient.closeConnect();// 關閉連線 } }
}