package com.sam.tool; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.jpedal.utils.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * FTP工具類 * * @author wl */ public class FtpUtils { private FTPClient ftpClient = null; private String server; private int port; private String userName; private String userPassword; public FtpUtils(String server, int port, String userName, String userPassword) { this.server = server; this.port = port; this.userName = userName; this.userPassword = userPassword; } /** * 連接服務器 * * @return 連接成功與否 true:成功, false:失敗 */ public boolean open() { if (ftpClient != null && ftpClient.isConnected()) { return true; } try { ftpClient = new FTPClient(); // 連接 ftpClient.connect(this.server, this.port); ftpClient.login(this.userName, this.userPassword); setFtpClient(ftpClient); // 檢測連接是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.close(); System.err.println("FTP server refused connection."); System.exit(1); } System.out.println("open FTP success:" + this.server + ";port:" + this.port + ";name:" + this.userName + ";pwd:" + this.userPassword); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 設置上傳模式.binally or ascii return true; } catch (Exception ex) { this.close(); ex.printStackTrace(); return false; } } /** * 切換到父目錄 * * @return 切換結果 true:成功, false:失敗 */ private boolean changeToParentDir() { try { return ftpClient.changeToParentDirectory(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 改變當前目錄到指定目錄 * * @param dir 目的目錄 * @return 切換結果 true:成功,false:失敗 */ private boolean cd(String dir) { try { return ftpClient.changeWorkingDirectory(dir); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 獲取目錄下所有的文件名稱 * * @param filePath 指定的目錄 * @return 文件列表, 或者null */ private FTPFile[] getFileList(String filePath) { try { return ftpClient.listFiles(filePath); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 層層切換工作目錄 * * @param ftpPath 目的目錄 * @return 切換結果 */ public boolean changeDir(String ftpPath) { if (!ftpClient.isConnected()) { return false; } try { // 將路徑中的斜槓統一 char[] chars = ftpPath.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpPath = sbStr.toString(); if (ftpPath.indexOf('/') == -1) { // 只有一層目錄 ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); } else { // 多層目錄循環創建 String[] paths = ftpPath.split("/"); for (int i = 0; i < paths.length; i++) { ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1")); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 循環創建目錄,並且創建完目錄後,設置工作目錄爲當前創建的目錄下 * * @param ftpPath 需要創建的目錄 * @return */ public boolean mkDir(String ftpPath) { if (!ftpClient.isConnected()) { return false; } try { // 將路徑中的斜槓統一 char[] chars = ftpPath.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpPath = sbStr.toString(); System.out.println("ftpPath:" + ftpPath); if (ftpPath.indexOf('/') == -1) { // 只有一層目錄 ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); } else { // 多層目錄循環創建 String[] paths = ftpPath.split("/"); for (int i = 0; i < paths.length; i++) { ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1")); ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1")); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 上傳文件到FTP服務器 * * @param localDirectoryAndFileName 本地文件目錄和文件名 * @param ftpFileName 上傳到服務器的文件名 * @param ftpDirectory FTP目錄如:/path1/pathb2/,如果目錄不存在會自動創建目錄 * @return */ public boolean upload(String localDirectoryAndFileName) { String ftpFileName = String.valueOf(System.currentTimeMillis()); if (!ftpClient.isConnected()) { return false; } boolean flag = false; if (ftpClient != null) { File srcFile = new File(localDirectoryAndFileName); ftpFileName = srcFile.getName(); FileInputStream fis = null; try { fis = new FileInputStream(srcFile); // 創建目錄 ftpClient.setBufferSize(100000); ftpClient.setControlEncoding("UTF-8"); // 設置文件類型(二進制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 上傳 flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fis); } catch (Exception e) { this.close(); e.printStackTrace(); return false; } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("上傳文件成功,本地文件名: " + localDirectoryAndFileName ); return flag; } /** * 從FTP服務器上下載文件 * * @param ftpDirectoryAndFileName ftp服務器文件路徑,以/dir形式開始 * @param localDirectoryAndFileName 保存到本地的目錄 * @return */ public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) { if (!ftpClient.isConnected()) { return false; } ftpClient.enterLocalPassiveMode(); // Use passive mode as default try { // 將路徑中的斜槓統一 char[] chars = ftpDirectoryAndFileName.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpDirectoryAndFileName = sbStr.toString(); String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/")); String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1); this.changeDir(filePath); ftpClient.retrieveFile(new String(fileName.getBytes(), "iso-8859-1"), new FileOutputStream(localDirectoryAndFileName)); // download // file System.out.println(ftpClient.getReplyString()); // check result System.out.println("從ftp服務器上下載文件:" + ftpDirectoryAndFileName + ", 保存到:" + localDirectoryAndFileName); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * 返回FTP目錄下的文件列表 * * @param pathName * @return */ public String[] getFileNameList(String pathName) { try { return ftpClient.listNames(pathName); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 刪除FTP上的文件 * * @param ftpDirAndFileName 路徑開頭不能加/,比如應該是test/filename1 * @return */ public boolean deleteFile(String ftpDirAndFileName) { if (!ftpClient.isConnected()) { return false; } try { return ftpClient.deleteFile(ftpDirAndFileName); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 刪除FTP目錄 * * @param ftpDirectory * @return */ public boolean deleteDirectory(String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } try { return ftpClient.removeDirectory(ftpDirectory); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 關閉鏈接 */ public void close() { try { if (ftpClient != null && ftpClient.isConnected()) { ftpClient.disconnect(); } System.out.println("成功關閉連接,服務器ip:" + this.server + ", 端口:" + this.port); } catch (Exception e) { e.printStackTrace(); } } public FTPClient getFtpClient() { return ftpClient; } public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; } public static void main(String[] args) { FtpUtils f = new FtpUtils("192.168.162.100", 21, "uftp", "admin"); try { if (f.open()) { //上傳 f.upload("d:/1.txt"); //遍歷 FTPFile[] list = f.getFileList("test1"); for (FTPFile file : list) { String name = file.getName(); System.out.println("--" + new String(name.getBytes("iso-8859-1"), "GB2312")); } //只遍歷指定目錄下的文件名 String[] names = f.getFileNameList("test1"); for (String name : names) { System.out.println(new String(name.getBytes("iso-8859-1"), "GB2312")); } //下載 boolean b = f.get("/test1/測試2.txt", "d:/text.txt"); System.out.println(b); //刪除 String ftpDirAndFileName = "test1/測試.txt"; boolean be = f.deleteFile(new String(ftpDirAndFileName.getBytes(), "iso-8859-1")); System.out.println(be); //刪除目錄 boolean delf = f.deleteDirectory("test1"); System.out.println(delf); f.close(); } } catch (Exception e) { e.printStackTrace(); } } }
上傳文件到FTP服務器用到的工具類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.