pom引用:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
代碼:
package com.suncreate.wifi.tool; import org.apache.commons.io.IOUtils; import org.apache.commons.net.PrintCommandListener; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.*; import java.util.ArrayList; import java.util.List; @Service public class FtpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class); private static final String SEPARATOR_CHAR = "/"; private static final String CURRENT_DIR_CHAR = "."; private static final String PARENT_DIR_CHAR = ".."; private static FTPClient ftp = new FTPClient(); private List<String> fileNameList = new ArrayList<>(); public List<String> getFileNameList() { return fileNameList; } @PostConstruct public void init() { login("127.0.0.1", 21, "admin", "123456"); } @PreDestroy public void destroy() { disConnection(); } public FtpUtils() { } /** * 重載構造函數 * * @param isPrintCommmand 是否打印與FTPServer的交互命令 */ public FtpUtils(boolean isPrintCommmand) { if (isPrintCommmand) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); } } /** * 登陸FTP服務器 * * @param host FTPServer IP地址 * @param port FTPServer 端口 * @param username FTPServer 登陸用戶名 * @param password FTPServer 登陸密碼 * @return 是否登錄成功 * @throws IOException */ public boolean login(String host, int port, String username, String password) { if (ftp.isAvailable()) { return true; } try { ftp.connect(host, port); } catch (IOException e) { LOGGER.error("can not connect ftp!", e); } if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { try { if (ftp.login(username, password)) { ftp.enterLocalPassiveMode(); ftp.setControlEncoding("UTF-8"); ftp.setFileType(FTP.BINARY_FILE_TYPE); return true; } } catch (IOException e) { LOGGER.error("can not login ftp!", e); } } return false; } /** * 清空集合 */ public void clearList() { fileNameList.clear(); } /** * 關閉數據鏈接 * * @throws IOException */ public void disConnection() { try { if (ftp.isConnected()) { ftp.logout(); ftp.disconnect(); LOGGER.info("close ftp connection success!"); } } catch (IOException e) { LOGGER.error("close ftp connection failed!", e); } } /** * 遞歸遍歷目錄下面指定的文件名 * * @param pathName 需要遍歷的目錄,必須以"/"開始和結束 * @param ext 文件的擴展名 * @throws IOException */ public void listFileName(String pathName, String ext) { if (pathName.startsWith(SEPARATOR_CHAR) && pathName.endsWith(SEPARATOR_CHAR)) { //更換目錄到當前目錄 FTPFile[] files = new FTPFile[]{}; try { ftp.changeWorkingDirectory(pathName); files = ftp.listFiles(); } catch (IOException e) { LOGGER.info("traverse ftp dir failed!", e); } for (FTPFile file : files) { if (file.isFile()) { if (file.getName().endsWith(ext)) { fileNameList.add(pathName + file.getName()); } } } } } /** * 目錄下面是否存在指定的文件 */ public int fileExist(String pathName) { int length = 0; //更換目錄到當前目錄 try { ftp.changeWorkingDirectory(pathName); FTPFile[] ftpFiles = ftp.listFiles(pathName); length = ftpFiles.length; } catch (IOException e) { e.printStackTrace(); } return length; } /** * 遍歷文件 * * @param pathName 根路徑 */ public void listFileName(String pathName) { listFileName(pathName, "zip"); } /** * 獲取圖片流 * * @param ftpPath 根路徑 */ public byte[] downloadFtpFile(String ftpPath) { byte[] file = null; InputStream inputStream = null; try { inputStream = ftp.retrieveFileStream(ftpPath); file = IOUtils.toByteArray(inputStream); } catch (Exception e) { LOGGER.error("download ftp failed!", e); } finally { if (null != inputStream) { try { inputStream.close(); if (ftp.completePendingCommand()) { LOGGER.info("download fileName={} success!", ftpPath); } else { LOGGER.warn("download fileName={} failed!", ftpPath); } } catch (IOException e) { LOGGER.error("close ftp inputStream failed!", e); } } } return file; } /** * 刪除ftp上的文件 * * @param ftpFileName * @return true || false */ public boolean removeFtpFile(String ftpFileName) { boolean flag = false; try { flag = ftp.deleteFile(ftpFileName); if (flag) { LOGGER.info("delete fileName={} success!", ftpFileName); } else { LOGGER.warn("delete fileName={} failed!", ftpFileName); } } catch (IOException e) { LOGGER.error("delete file failed!", e); } return flag; } public static void main(String[] args) { System.out.println(System.getProperty("user.dir")); return; /* FtpUtils ftpUtils = new FtpUtils(); ftpUtils.login("34.8.8.206", 21, "admin", "admin"); ftpUtils.listFileName("/D:/ftproot/2019gakm/"); ftpUtils.listFileName("/D:/ftproot/2019yryp/"); for (String arFile : ftpUtils.getFileNameList()) { System.out.println("filename=" + arFile); byte[] file = ftpUtils.downloadFtpFile(arFile); System.out.println("bytefile=" + file); } ftpUtils.disConnection();*/ } }