Java FTP操作
pom引用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<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>
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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();*/ } }