package net.eshui.util.ftp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Calendar; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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; /** * @Title:FTPUtil * @Description: * @Company:www.eshui.net 提供ftp 上傳 下載 ,文件上傳和下載需要優化downloadFile() * uploadDirectory() */ public class FTPUtil { private FTPClient ftpClient; private String IP; private int port; private String userName; private String password; private static final Log LOG = LogFactory.getLog(FTPUtil.class); /** * 構造函數 * * @param IP * FTP服務器地址 * @param userName * FTP服務器用戶名 * @param passWord * FTP服務器密碼 */ public FTPUtil(String IP, int port, String userName, String password) { this.IP = IP; this.port = port; this.userName = userName; this.password = password; this.ftpClient = new FTPClient(); } /** * @return 判斷是否登入成功 * */ public boolean login() { boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); // this.ftpClient.setControlEncoding("GBK"); this.ftpClient.configure(ftpClientConfig); try { if (this.port > 0) { this.ftpClient.connect(this.IP, this.port); } else { this.ftpClient.connect(IP); } // FTP服務器連接回答 int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); if (LOG.isDebugEnabled()) LOG.debug("登錄FTP服務失敗!"); return isLogin; } this.ftpClient.login(this.userName, this.password); // 設置傳輸協議 this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); if (LOG.isDebugEnabled()) LOG.debug("恭喜" + this.userName + "成功登陸FTP服務器"); isLogin = true; } catch (Exception e) { LOG.error(this.userName + "登錄FTP服務失敗!" + e.getMessage()); } this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(3 * 1000); return isLogin; } /** * 退出關閉服務器鏈接 */ public void logOut() { if (null != this.ftpClient && this.ftpClient.isConnected()) { try { boolean reuslt = this.ftpClient.logout();// 退出FTP服務器 if (reuslt) { if (LOG.isDebugEnabled()) LOG.debug("成功退出服務器"); } } catch (IOException e) { LOG.error("退出FTP服務器異常!" + e.getMessage()); } finally { try { this.ftpClient.disconnect();// 關閉FTP服務器的連接 } catch (IOException e) { LOG.error("關閉FTP服務器的連接異常!"); } } } } /** * 上傳文件 * * @param localFile * 本地文件 * @param remoteUpLoadePath * 上傳路徑 * @return */ public boolean uploadFile(String localFile, String remoteUpLoadePath) { return uploadFile(new File(localFile), remoteUpLoadePath); } /*** * 上傳Ftp文件 * * @param localFile * 當地文件 * @param remoteUpLoadePath上傳服務器路徑 * - 應該以/結束 * */ public boolean uploadFile(File localFile, String remoteUpLoadePath) { BufferedInputStream inStream = null; boolean success = false; try { inStream = new BufferedInputStream(new FileInputStream(localFile)); createDirectory(remoteUpLoadePath); // 項目集成調用StreamUtil方法來實現 if (LOG.isDebugEnabled()) LOG.debug(localFile.getName() + "開始上傳....."); success = this.ftpClient.storeFile(localFile.getName(), inStream); if (success == true) { if (LOG.isDebugEnabled()) LOG.debug(localFile.getName() + "上傳成功"); return success; } } catch (FileNotFoundException e) { LOG.error(localFile + "未找到"); } catch (IOException e) { LOG.error("上傳文件IO出錯!" + e.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /*** * 上傳Ftp文件 * * @param localFile * 當地文件 * @param remoteUpLoadePath上傳服務器路徑 * - 應該以/結束 * */ public boolean uploadFile(File localFile, String remoteUpLoadePath,String fileName) { BufferedInputStream inStream = null; boolean success = false; try { inStream = new BufferedInputStream(new FileInputStream(localFile)); createDirectory(remoteUpLoadePath); // 項目集成調用StreamUtil方法來實現 if (LOG.isDebugEnabled()) LOG.debug(localFile.getName() + "開始上傳....."); success = this.ftpClient.storeFile(fileName, inStream); if (success == true) { if (LOG.isDebugEnabled()) LOG.debug(localFile.getName() + "上傳成功"); return success; } } catch (FileNotFoundException e) { LOG.error(localFile + "未找到"); } catch (IOException e) { LOG.error("上傳文件IO出錯!" + e.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /*** * 上傳Ftp文件 * * @param in * 數據流 * @param remoteUpLoadePath上傳服務器路徑 * @param file * 存儲名稱 * @throws IOException * */ public boolean uploadFile(String remoteUpLoadePath, String remotefileName, byte[] in) throws IOException { InputStream inStream = null; boolean success = false; try { // 項目集成調用StreamUtil方法來實現 inStream = ByteArrayInputStream(in); if (LOG.isDebugEnabled()) LOG.debug(remotefileName + "開始上傳....."); this.ftpClient.changeWorkingDirectory(remoteUpLoadePath); //切換到遠程目錄 success = this.ftpClient.storeFile(remotefileName, inStream); if (success == true) { if (LOG.isDebugEnabled()) LOG.debug(remotefileName + "上傳成功"); return success; } } catch (IOException e) { LOG.error("上傳文件IO出錯!" + e.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /*** * 上傳Ftp文件 * * @param in * 數據流 * @param remoteUpLoadePath上傳服務器路徑 * @param file * 存儲名稱 * @throws IOException * */ public boolean uploadFile(String remoteUpLoadePath, String remoteFileName, InputStream inStream) throws IOException { //InputStream inStream = null; boolean success = false; try { // 項目集成調用StreamUtil方法來實現 //inStream = ByteArrayInputStream(in); if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "開始上傳....."); this.ftpClient.changeWorkingDirectory(remoteUpLoadePath); //切換到遠程目錄 success = this.ftpClient.storeFile(new String(remoteFileName.getBytes("GBK") , "iso-8859-1") , inStream); if (success == true) { if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "上傳成功"); return success; } } catch (IOException e) { LOG.error("上傳文件IO出錯!" + e.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /** * byte 數組 轉換流 * * @param in * @return */ private InputStream ByteArrayInputStream(byte[] in) { ByteArrayInputStream is = new ByteArrayInputStream(in); return is; } // 項目集成調用StreamUtil方法來實現 private byte[] input2byte(InputStream inStream) throws IOException { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int rc = 0; while ((rc = inStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } byte[] in2b = swapStream.toByteArray(); return in2b; } /*** * 下載文件 * * @param remoteFileName * 待下載文件名稱 * @param localDires * 下載到當地那個路徑下 * @param remoteDownLoadPath * remoteFileName所在的路徑 * */ public boolean downloadFile(String localDires, String remoteFileName, String remoteDownLoadPath) { String strFilePath = converPath(localDires) + remoteFileName; BufferedOutputStream outStream = null; boolean success = false; try { this.ftpClient.changeWorkingDirectory(converPath(remoteDownLoadPath)); outStream = new BufferedOutputStream(new FileOutputStream(strFilePath)); if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "開始下載...."); success = this.ftpClient.retrieveFile(remoteFileName, outStream); if (success == true) { if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "成功下載到" + strFilePath); return success; } } catch (Exception e) { LOG.error(remoteFileName + "下載失敗"); } finally { if (null != outStream) { try { outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } if (success == false) { if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "下載失敗!!!"); } return success; } /*** * 下載文件 * * @param remoteFileName * 待下載文件名稱 * @param localDires * 下載到當地那個路徑下 * @param remoteDownLoadPath * remoteFileName所在的路徑 * @throws IOException * */ public byte[] downloadFile(String remoteFileName, String remoteDownLoadPath) throws IOException { InputStream inStream = null; byte[] retBytes = null; try { // Properties prop = System.getProperties(); // String os = prop.getProperty("os.name"); // if(os.startsWith("win") || os.startsWith("Win")){ // remoteDownLoadPath = remoteDownLoadPath.replace("\\","/"); // } // boolean b=ftpClient.changeWorkingDirectory("/2016"); this.ftpClient.changeWorkingDirectory(remoteDownLoadPath.trim()); if (LOG.isDebugEnabled()) LOG.debug(remoteFileName + "開始下載...."); inStream = this.ftpClient.retrieveFileStream(remoteFileName.trim()); retBytes = input2byte(inStream); } catch (Exception e) { LOG.error(remoteFileName + "下載失敗"); } finally { if (null != inStream) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return retBytes; } /*** * @上傳文件夾 * @param localDirectory * 當地文件夾 * @param remoteDirectoryPath * Ftp 服務器路徑 以目錄"/"結束 * @throws IOException * @throws UnsupportedEncodingException * */ public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) throws UnsupportedEncodingException, IOException { File src = new File(localDirectory); File[] allFile = src.listFiles(); for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (!allFile[currentFile].isDirectory()) { String srcName = allFile[currentFile].getPath().toString(); uploadFile(new File(srcName), remoteDirectoryPath); } } for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (allFile[currentFile].isDirectory()) { // 遞歸 String path = converPath(remoteDirectoryPath) + allFile[currentFile].getName(); createDirectory(allFile[currentFile].getName().toString()); uploadDirectory(allFile[currentFile].getPath().toString(), path); } } return true; } /*** * @下載文件夾 * @param localDirectoryPath本地地址 * @param remoteDirectory * 遠程文件夾 * */ public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) { remoteDirectory = converPath(remoteDirectory); localDirectoryPath = converPath(localDirectoryPath); try { new File(localDirectoryPath).mkdirs(); FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory); for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (!allFile[currentFile].isDirectory()) { downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory); } } for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (allFile[currentFile].isDirectory()) { String strRemoteDirectoryPath = converPath(remoteDirectory) + allFile[currentFile].getName(); String strLocalDirectoryPath = converPath(localDirectoryPath) + allFile[currentFile].getName(); new File(converPath(strLocalDirectoryPath)).mkdirs(); // this.ftpClient.changeWorkingDirectory(converPath(strRemoteDirectoryPath)); downLoadDirectory(converPath(strLocalDirectoryPath), converPath(strRemoteDirectoryPath)); } } } catch (IOException e) { LOG.error("下載文件夾失敗!" + e.toString()); return false; } return true; } /** * 根據路徑進行創建文件,解決兼容問題 * * @param path * @return * @throws IOException * @throws UnsupportedEncodingException */ public boolean createDirectory(String path) throws UnsupportedEncodingException, IOException { path = converPath(path); String directory = path.substring(0, path.lastIndexOf("/") + 1); if (!directory.equalsIgnoreCase("/") && !this.ftpClient.changeWorkingDirectory(directory)) { // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄 int start = 0; int end = 0; if (directory.startsWith("/")) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory = path.substring(start, end); if (!ftpClient.changeWorkingDirectory(subDirectory)) { if (ftpClient.makeDirectory(subDirectory)) { ftpClient.changeWorkingDirectory(subDirectory); } else { if (LOG.isDebugEnabled()) LOG.debug("創建目錄失敗!"); return false; } } start = end + 1; end = directory.indexOf("/", start); // 檢查所有目錄是否創建完畢 if (end <= start) { break; } } } return true; } /** * 增加目錄結尾標識“/” * * @param path * @return */ private String converPath(String path) { if (!path.trim().endsWith("/")) path = path + "/"; return path; } /** * 讀取圖片 文件 * * @param imgPath * @return */ public static byte[] imageToByteArray(String imgPath) { BufferedInputStream in; try { in = new BufferedInputStream(new FileInputStream(imgPath)); ByteArrayOutputStream out = new ByteArrayOutputStream(); int size = 0; byte[] temp = new byte[1024]; while ((size = in.read(temp)) != -1) { out.write(temp, 0, size); } in.close(); return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 根據日期轉換為路徑 目錄到分鍾 * * @return */ public String sysDate2path2minute() { Calendar date = Calendar.getInstance(); String rootDir = ""; String path = rootDir + "/" + date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + date.get(Calendar.HOUR_OF_DAY) + "/" + date.get(Calendar.MINUTE); return path; } /** * 根據日期轉換為路徑 目錄到小時 * * @return */ public String sysDate2path2hour() { Calendar date = Calendar.getInstance(); String rootDir = ""; String path = rootDir + "/" + date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + date.get(Calendar.HOUR_OF_DAY); return path; } /** * 根據日期轉換為路徑 目錄到天 * * @return */ public String sysDate2path2day() { Calendar date = Calendar.getInstance(); String rootDir = ""; String path = rootDir + "/" + date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + date.get(Calendar.DAY_OF_MONTH); return path; } /** * * 刪除文件 * * * @param remoteUpLoadePath * FTP服務器保存目錄 * * @param remoteFileName * 要刪除的文件名稱 * * @return */ public boolean deleteFile(String remoteUpLoadePath, String remoteFileName) { boolean flag = false; try { //切換FTP目錄 this.ftpClient.changeWorkingDirectory(remoteUpLoadePath); //刪除 this.ftpClient.dele(remoteFileName); flag = true; } catch (Exception e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return flag; } public static void main(String[] args) throws FileNotFoundException { long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { FTPUtil ftp = new FTPUtil("192.168.1.79", 8888, "123", "12345"); ftp.login(); File file = new File("D:\\pic\\" + i % 8 + ".JPG"); InputStream is = new FileInputStream(file); ftp.uploadFile(file, "/home/ftp", i + ".jpg"); ftp.logOut(); System.out.println(i + "傳輸完成!"); } long end = System.currentTimeMillis(); System.out.println("總時間毫秒:" + (end - start)); } }