上傳和下載Ftp服務器文件或文件夾
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.TimeZone;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;
public class FtpUtil { private FTPClient ftpClient; private String strIp; private int intPort; private String user; private String password;
private static Logger logger = Logger.getLogger(FtpUtil.class); /* * * Ftp構造函數 */ public FtpUtil(String strIp, int intPort, String user, String Password) { this.strIp = strIp; this.intPort = intPort; this.user = user; this.password = Password; this.ftpClient = new FTPClient(); } /** * @return 判斷是否登入成功 * */ public boolean ftpLogin() { boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); this.ftpClient.setControlEncoding("UTF-8"); this.ftpClient.configure(ftpClientConfig); try { if (this.intPort > 0) { this.ftpClient.connect(this.strIp, this.intPort); } else { this.ftpClient.connect(this.strIp); } // FTP服務器連接回答 int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); System.out.println("登錄FTP服務失敗!"); return isLogin; } this.ftpClient.login(this.user, this.password); // 設置傳輸協議 this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); System.out.println("恭喜" + this.user + "成功登陸FTP服務器"); //logger.info("恭喜" + this.user + "成功登陸FTP服務器"); isLogin = true; } catch (Exception e) { e.printStackTrace(); System.out.println(this.user + "登錄FTP服務失敗!" + e.getMessage()); } this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(30 * 1000); return isLogin; } /** * @退出關閉服務器鏈接 * */ public void ftpLogOut() { if (null != this.ftpClient && this.ftpClient.isConnected()) { try { boolean reuslt = this.ftpClient.logout();// 退出FTP服務器 if (reuslt) { System.out.println("成功退出服務器"); } } catch (IOException e) { e.printStackTrace(); System.out.println("退出FTP服務器異常!" + e.getMessage()); } finally { try { this.ftpClient.disconnect();// 關閉FTP服務器的連接 } catch (IOException e) { e.printStackTrace(); logger.warn("關閉FTP服務器的連接異常!"); } } } } /*** * 上傳Ftp文件 * * @param localFile * 當地文件 * @param romotUpLoadePath上傳服務器路徑 * - 應該以/結束 * */ public boolean uploadFile(File localFile, String romotUpLoadePath) { BufferedInputStream inStream = null; boolean success = false; try { this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改變工作路徑 inStream = new BufferedInputStream(new FileInputStream(localFile)); logger.info(localFile.getName() + "開始上傳....."); success = this.ftpClient.storeFile(localFile.getName(), inStream); if (success == true) { logger.info(localFile.getName() + "上傳成功"); return success; } } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(localFile + "未找到"); } catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /*** * 下載文件 * * @param remoteFileName * 待下載文件名稱 * @param localDires * 下載到當地那個路徑下 * @param remoteDownLoadPath * remoteFileName所在的路徑 * */ public boolean downloadFile(String remoteFileName,String localFileName, String localDires, String remoteDownLoadPath) { String strFilePath = localDires + remoteFileName; if(localFileName!=null && localFileName.length()>0){ strFilePath=localDires+localFileName; } BufferedOutputStream outStream = null; boolean success = false; try { this.ftpClient.changeWorkingDirectory(remoteDownLoadPath); FTPFile[] fs = ftpClient.listFiles(); for (FTPFile ff : fs) { System.out.println(ff.getName()); } outStream = new BufferedOutputStream(new FileOutputStream( strFilePath)); System.out.println(remoteFileName + "開始下載...."); success = this.ftpClient.retrieveFile(remoteFileName, outStream); if (success == true) { System.out.println(remoteFileName + "成功下載到" + strFilePath); return success; } } catch (Exception e) { e.printStackTrace(); System.out.println(remoteFileName + "下載失敗"); } finally { if (null != outStream) { try { outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } if (success == false) { System.out.println(remoteFileName + "下載失敗!!!"); } return success; } /*** * @上傳文件夾 * @param localDirectory * 當地文件夾 * @param remoteDirectoryPath * Ftp 服務器路徑 以目錄"/"結束 * */ public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) { File src = new File(localDirectory); try { remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/"; this.ftpClient.makeDirectory(remoteDirectoryPath); // ftpClient.listDirectories(); } catch (IOException e) { e.printStackTrace(); logger.info(remoteDirectoryPath + "目錄創建失敗"); } File[] allFile = src.listFiles(); System.out.println(allFile); 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()) { // 遞歸 uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath); } } return true; } /*** * @下載文件夾 * @param localDirectoryPath本地地址 * @param remoteDirectory * 遠程文件夾 * */ public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) { try { String fileName = new File(remoteDirectory).getName(); localDirectoryPath = localDirectoryPath + fileName + "//"; 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 = remoteDirectory + "/" + allFile[currentFile].getName(); downLoadDirectory(localDirectoryPath, strremoteDirectoryPath); } } } catch (IOException e) { e.printStackTrace(); logger.info("下載文件夾失敗"); return false; } return true; } // FtpClient的Set 和 Get 函數 public FTPClient getFtpClient() { return ftpClient; } public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; }
// public static void main(String[] args) { // try { //// FtpUtil ftp = new FtpUtil(url, port, username, passwd); //// ftp.ftpLogin(); // // 上傳文件夾 // // ftp.uploadDirectory("D:\test\2013", "/2013"); // // 下載文件夾 // String temp = "/apk/app-54aa5a6c3b46c0e3f0b8400f/02594934725bb4fed5456f8b5133dfaa.apk"; // String filename = temp.substring(temp.lastIndexOf("/") + 1, temp.length()); // String filepath = temp.substring(0, temp.lastIndexOf("/") + 1); // System.out.println(filename); // System.out.println(filepath); //// ftp.downloadFile(filename, "test.apk", "d://", filepath); //// ftp.ftpLogOut(); // } catch (Exception e) { // e.printStackTrace(); // } // // } }</pre>