java ftp 单个上传 单个下载 批量上传 批量下载

tech2025-07-23  4

依赖

<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.7</version> </dependency>

完整的JAVA工具类

package test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPUtil { protected static Logger logger = Logger.getLogger(FTPUtil.class.getName()); /** * FTP地址 **/ private static String ftpHost; /** * FTP端口 **/ private static int ftpPort = 21; /** * FTP用户名 **/ private static String ftpUsername; /** * FTP密码 **/ private static String ftpPassword; /** * FTP协议里面,规定文件名编码为iso-8859-1 **/ private static String serverCharset = "ISO-8859-1"; /** * UTF-8字符编码 **/ private static final String CHARSET_UTF8 = "UTF-8"; /** * 设置缓冲区大小4M **/ private static final int BUFFER_SIZE = 1024 * 1024 * 4; /** * 加载ftp配置信息 */ static { try { Properties properties = new Properties(); InputStream in = FTPUtil.class.getClassLoader().getResourceAsStream("application.properties"); properties.load(in); ftpHost = properties.getProperty("ftp.host"); String port = properties.getProperty("ftp.port"); if (port != null && !"".equals(port)) { ftpPort = Integer.valueOf(port); } ftpUsername = properties.getProperty("ftp.username"); ftpPassword = properties.getProperty("ftp.password"); in.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 下载单个文件 * * @param ftpFilePath * /usr/java/test/test3/CorsApplicationTests.java * @param localPath * F:\\bak\\bak19\\v6\\v1 * @return */ public static boolean get(String ftpFilePath, String localPath) { FTPClient ftpClient = null; try { // build client ftpClient = buildClient(); // get ftpFilePath = ftpFilePath.replaceAll("\\\\", "/"); int index = ftpFilePath.lastIndexOf("/"); String fileName = ftpFilePath.substring(index + 1); String ftpPath = ftpFilePath.substring(0, index); FileOutputStream fos = new FileOutputStream(new File(localPath + "/" + fileName)); ftpClient.changeWorkingDirectory(ftpPath); boolean isSucess = ftpClient.retrieveFile(fileName, fos); fos.close(); return isSucess; } catch (Exception e) { e.printStackTrace(); logger.warning("ftp get fail:" + e.getMessage()); } return false; } /** * 上传单个文件 * * @param localFilePath * F:\\bak\\bak19\\v6\\v1\\CorsApplication.java * @param ftpPath * /usr/java/test/ * @return */ public static boolean push(String localFilePath, String ftpPath) { FTPClient ftpClient = null; try { // build client ftpClient = buildClient(); // push ftpPath = ftpPath.replaceAll("\\\\", "/"); File file = new File(localFilePath); FileInputStream fis = new FileInputStream(file); ftpClient.changeWorkingDirectory(ftpPath); boolean isSucess = ftpClient.storeFile(file.getName(), fis); fis.close(); return isSucess; } catch (Exception e) { e.printStackTrace(); logger.warning("ftp push fail:" + e.getMessage()); } return false; } /** * 下载整个文件夹 * * @param ftpPath * /usr/local/tmp * @param localPath * F:/bak/v1 * @return */ public static boolean downloadFolder(String ftpPath, String localPath) { FTPClient ftpClient = null; try { // build client ftpClient = buildClient(); // downloadFiles File savePathFile = new File(localPath); if (!savePathFile.exists()) { savePathFile.mkdirs(); } downloadFiles(ftpClient, ftpPath, localPath); return true; } catch (Exception e) { e.printStackTrace(); logger.warning("ftp download fail:" + e.getMessage()); } finally { // close close(ftpClient); } return false; } /** * 上传整个文件夹 * * @param localPath * F:\\bak\\bak19\\v6\\v1 * @param ftpPath * /usr/java/test/test3 * @return */ public static boolean uploadFolder(String localPath, String ftpPath) { FTPClient ftpClient = null; try { // build client ftpClient = buildClient(); // uploadFiles uploadFiles(ftpClient, localPath, ftpPath); return true; } catch (Exception e) { e.printStackTrace(); logger.warning("ftp uploadFolder fail:" + e.getMessage()); } finally { // close close(ftpClient); } return false; } /** * 递归下载所有文件 * * @param ftpClient * @param ftpPath * @param localPath * @return */ public static boolean downloadFiles(FTPClient ftpClient, String ftpPath, String localPath) throws IOException { // 判断是否存在该目录 if (!ftpClient.changeWorkingDirectory(ftpPath)) { logger.warning(ftpPath + "该目录不存在"); return Boolean.FALSE; } FTPFile[] ftpFileArr = ftpClient.listFiles(); if (ftpFileArr == null || ftpFileArr.length == 0) { return Boolean.FALSE; } for (FTPFile file : ftpFileArr) { String fileName = file.getName(); if (file.isFile()) { String ftpName = new String(fileName.getBytes(serverCharset), CHARSET_UTF8); File saveFile = new File(localPath + '/' + ftpName); try (FileOutputStream fos = new FileOutputStream(saveFile)) { ftpClient.retrieveFile(file.getName(), fos); } catch (IOException e) { e.printStackTrace(); } } if (file.isDirectory()) { String dirName = localPath + "/" + fileName; File dirFile = new File(dirName); if (!dirFile.exists()) { dirFile.mkdirs(); } downloadFiles(ftpClient, ftpPath + "/" + fileName, dirName); } } return Boolean.TRUE; } /** * 递归上传所有文件 * * @param localPath * @param ftpPath * @return */ public static boolean uploadFiles(FTPClient ftpClient, String localPath, String ftpPath) throws IOException { ftpClient.changeWorkingDirectory(ftpPath); File localPathFile = new File(localPath); if (!localPathFile.exists()) { return false; } File[] fileArr = localPathFile.listFiles(); for (File file : fileArr) { if (file.isFile()) { try (FileInputStream fis = new FileInputStream(file)) { ftpClient.storeFile(file.getName(), fis); } catch (IOException e) { e.printStackTrace(); } } if (file.isDirectory()) { String pathname = ftpPath + "/" + file.getName(); ftpClient.makeDirectory(pathname); uploadFiles(ftpClient, file.getPath(), pathname); } } return true; } /** * 构造FTPClient * * @return */ private static FTPClient buildClient() throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setConnectTimeout(1000 * 60); ftpClient.connect(ftpHost, ftpPort); ftpClient.login(ftpUsername, ftpPassword); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 限制缓冲区大小 ftpClient.setBufferSize(BUFFER_SIZE); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.logout(); ftpClient.disconnect(); logger.warning("FTP服务器连接失败"); throw new Exception("connect ftp server fail"); } // 设置被动模式,开通一个端口来传输数据 ftpClient.enterLocalPassiveMode(); return ftpClient; } /** * 关闭FTP客户端 * * @param ftpClient */ private static void close(FTPClient ftpClient) { if (ftpClient != null) { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); logger.warning("ftp logout fail:" + e.getMessage()); } } } public static void main(String[] args) { long lstart = System.currentTimeMillis(); // boolean isSuccess = FTPUtil.downloadFolder("/usr/java/test/test", // "F:\\bak\\bak19\\v6\\v1"); // boolean isSuccess = FTPUtil.uploadFolder("F:\\bak\\bak19\\v6\\v1", // "/usr/java/test/test3"); boolean isSuccess = FTPUtil.get("/usr/java/test/test3/IndexController.java", "F:\\bak\\bak19\\v6\\v1"); // boolean isSuccess = // FTPUtil.push("F:\\bak\\bak19\\v6\\v1\\CorsApplication.java","/usr/java/test/test/"); System.out.println("total time:" + (System.currentTimeMillis() - lstart) + " ms"); System.out.println("isSuccess:" + isSuccess); } }

配置文件application.properties

server.port=8000 ftp.host=192.168.152.128 ftp.port=21 ftp.username=administrator ftp.password=123456

 

最新回复(0)