Java實現FTP服務器的上傳、下載、刪除、查看文件列表
所需要的第三方jar包
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; /** * <p> * ftp連接管理(使用apache commons-net-1.4.1 lib) * </p> */ public class FtpClientUtil { private FTPClient ftpClient = null; private String server; private int port; private String userName; private String userPassword; public static void main(String[] args) { // 調用FTP傳輸g // FtpClientUtil f = new FtpClientUtil("10.50.20.8", 21, "suzy", // "123456"); // FtpClientUtil f = new FtpClientUtil("10.7.4.56",21,"root","wonder"); FtpClientUtil f = new FtpClientUtil("10.3.128.178", 21, "lu", "111"); // FtpClientUtil f = new // FtpClientUtil("10.50.20.213",21,"Administrator","administrator"); try { if (f.open()) { // f.getFtpClient().sendServer("quote PASV"); // f.getFtpClient().sendServer("quote PORT"); // f.mkDir("put2/5/6\\8\\9"); // f.mkDir("test6\\7/8/9"); // f.mkDir("test6/7/8/9"); // f.mkDir("test7"); // f.put("d:/1.txt", "中國.txt", "put3/測試/6\\8\\9");// 遠程路徑為相對路徑 f.get("/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/qunarlog.txt", "E:/111111111.txt");// 遠程路徑為相對路徑 f.close(); } } catch (Exception e) { e.printStackTrace(); } } public FtpClientUtil(String server, int port, String userName, String userPassword) { this.server = server; this.port = port; this.userName = userName; this.userPassword = userPassword; } /** * 鏈接到服務器 * * @return * @throws Exception */ 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); // 檢測連接是否成功 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(ftpClient.BINARY_FILE_TYPE); // 設置上傳模式.binally // or ascii return true; } catch (Exception ex) { // 關閉 this.close(); ex.printStackTrace(); return false; } } private boolean cd(String dir) throws IOException { if (ftpClient.changeWorkingDirectory(dir)) { return true; } else { return false; } } /** * 獲取目錄下所有的文件名稱 * * @param filePath * @return * @throws IOException */ private FTPFile[] getFileList(String filePath) throws IOException { FTPFile[] list = ftpClient.listFiles(); return list; } /** * 循環將設置工作目錄 */ 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(); // System.out.println("ftpPath"+ftpPath); if (ftpPath.indexOf('/') == -1) { // 只有一層目錄 // System.out.println("change"+ftpPath); ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); } else { // 多層目錄循環創建 String[] paths = ftpPath.split("/"); // String pathTemp = ""; for (int i = 0; i < paths.length; i++) { // System.out.println("change "+paths[i]); ftpClient.changeWorkingDirectory(new String(paths[i] .getBytes(), "iso-8859-1")); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 循環創建目錄,并且創建完目錄后,設置工作目錄為當前創建的目錄下 */ 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("/"); // String pathTemp = ""; 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 localPathAndFileName * 本地文件目錄和文件名 * @param ftpFileName * 上傳后的文件名 * @param ftpDirectory * FTP目錄如:/path1/pathb2/,如果目錄不存在回自動創建目錄 * @throws Exception */ public boolean put(String localDirectoryAndFileName, String ftpFileName, String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } boolean flag = false; if (ftpClient != null) { File srcFile = new File(localDirectoryAndFileName); FileInputStream fis = null; try { fis = new FileInputStream(srcFile); // 創建目錄 this.mkDir(ftpDirectory); ftpClient.setBufferSize(1024); 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 { IOUtils.closeQuietly(fis); } } System.out.println("success put file " + localDirectoryAndFileName + " to " + ftpDirectory + ftpFileName); return flag; } /** * 從FTP服務器上下載文件并返回下載文件長度 * * @param ftpDirectoryAndFileName * @param localDirectoryAndFileName * @return * @throws Exception */ public long get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) { long result = 0; if (!ftpClient.isConnected()) { return 0; } ftpClient.enterLocalPassiveMode(); // Use passive mode as default // because most of us are behind // firewalls these days. 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); // System.out.println("filePath | "+filePath); // System.out.println("fileName | "+fileName); this.changeDir(filePath); ftpClient.retrieveFile( new String(fileName.getBytes(), "iso-8859-1"), new FileOutputStream(localDirectoryAndFileName)); // download // file System.out.print(ftpClient.getReplyString()); // check result } catch (IOException e) { e.printStackTrace(); } System.out.println("Success get file" + ftpDirectoryAndFileName + " from " + localDirectoryAndFileName); return result; } /** * 返回FTP目錄下的文件列表 * * @param ftpDirectory * @return */ public List getFileNameList(String ftpDirectory) { List list = new ArrayList(); // if (!open()) // return list; // try { // DataInputStream dis = new DataInputStream(ftpClient // .nameList(ftpDirectory)); // String filename = ""; // while ((filename = dis.readLine()) != null) { // list.add(filename); // } // } catch (Exception e) { // e.printStackTrace(); // } return list; } /** * 刪除FTP上的文件 * * @param ftpDirAndFileName */ public boolean deleteFile(String ftpDirAndFileName) { if (!ftpClient.isConnected()) { return false; } //Todo return true; } /** * 刪除FTP目錄 * * @param ftpDirectory */ public boolean deleteDirectory(String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } //ToDo return true; } /** * 關閉鏈接 */ public void close() { try { if (ftpClient != null && ftpClient.isConnected()) ftpClient.disconnect(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Close Server Success :"+this.server+";port:"+this.port); } public FTPClient getFtpClient() { return ftpClient; } public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; } } //設置以什么文件的格式輸出 try { response.setContentType("application/octet-stream;charset=GB2312"); String downloadname=downName; response.setHeader("Content-Disposition","attachment; filename="+downloadname); if (filename!=null) { File file1=new File(folerDown); FileInputStream is=new FileInputStream(file1); byte []bbb=new byte[(int)file1.length()]; System.out.println("------bbb.length:"+bbb.length); is.read(bbb); is.close(); OutputStream out = response.getOutputStream(); out.write(bbb); out.close(); response.setStatus(response.SC_OK); file1.delete(); } else { System.out.println("----createExcelFile error!"); } } catch (Exception e) { System.out.println("----------ex in servlet:"+e); e.printStackTrace(); }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!