Java基于commons-net包实现FTP协议连接linux服务器进行文件夹上传与下载操作源码

mac2025-04-21  1

添加依赖

// https://mvnrepository.com/artifact/commons-net/commons-net compile group: 'commons-net', name: 'commons-net', version: '3.6' // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

代码示例

package com.xl; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.ftp.*; import java.io.*; import java.util.TimeZone; public class FTPTransFile { private static final String localDir = "F:\\look\\";//传输的源端目录 //destDir路径为搭建FTP服务器时设置的用户的主目录中的共享目录 //如果不是的话changeDir的结果会一直为false private static final String serverDir = "/pub/";//传输的目的端目录,目录以"/"结束 private static final String host = "192.168.0.101";//目的端的IP地址 private static final int port = 21; //目的端的端口号 private static final String userName = "ftpUser";//目的端的用户名 private static final String passWord = "1234";//目的端的密码 private static final String encoding = "UTF-8"; public static void main(String[] args) throws Exception { //连接目的端 FTPClient ftpClient = connect(host, port, userName, passWord); //上传文件夹 //uploadDirectory(ftpClient, localDir, serverDir); //下载文件夹 downLoadDirectory(ftpClient, localDir, serverDir); //关闭客户端连接 disconnect(ftpClient); } /** * 连接目的端server * * @param host 目的端IP地址 * @param port 目的端端口号 * @param userName 目的端FTP用户名 * @param passWord 目的端FTP密码 * @return 返回FTPClient */ public static FTPClient connect(String host, int port, String userName, String passWord) { FTPClient ftpClient = new FTPClient(); FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); try { //设置文件传输的编码 ftpClient.setControlEncoding(encoding); ftpClient.configure(ftpClientConfig); // 连接 FTP 服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftpClient.connect(host, port);// 连接FTP服务器 //登录 FTP 服务器 //如果传入的账号为空,则使用匿名登录,此时账号使用 "look",密码为空即可*/ if (StringUtils.isBlank(userName)) { ftpClient.login("look", ""); } else { ftpClient.login(userName, passWord); } // 设置传输协议 ftpClient.enterLocalPassiveMode(); //设置传输的文件类型 //BINARY_FILE_TYPE:二进制文件类型,ASCII_FILE_TYPE:ASCII传输方式,这是默认的方式 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 检验是否连接成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { //如果 FTP 服务器响应错误 中断传输、断开连接 //abort:中断文件正在进行的文件传输,成功时返回 true,否则返回 false //disconnect:断开与服务器的连接,并恢复默认参数值 ftpClient.abort(); ftpClient.disconnect(); System.err.println("[" + reply + "]:连接失败!"); } else { System.out.println("[" + reply + "]:连接成功!"); } return ftpClient; } catch (Exception e) { return null; } } public static void disconnect(FTPClient ftpClient) { if (ftpClient != null && ftpClient.isConnected()) { try { // 退出FTP服务器 ftpClient.logout(); System.out.println("退出FTP服务器成功!"); } catch (IOException e) { e.printStackTrace(); System.err.println("退出FTP服务器失败!" + e.getMessage()); } finally { try { // 关闭FTP服务器的连接 ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); System.err.println("关闭FTP服务器连接失败!"); } } } } /** * 文件上传 * * @param ftpClient FTP客户端 * @param localDir 传输的源端目录 * @param serverDir 传输的目的端目录 */ public static void uploadFile(FTPClient ftpClient, String localDir, String serverDir) { File file = null; FileInputStream inputStream = null; try { // 转移工作目录至指定目录下 boolean changeDir = ftpClient.changeWorkingDirectory(serverDir); System.out.println("改变工作目录: " + changeDir); if (changeDir) { file = new File(localDir); inputStream = new FileInputStream(file); boolean result = ftpClient.storeFile(new String(file.getName().getBytes(encoding), "iso-8859-1"), inputStream); if (result) { System.out.println("文件上传成功: " + file.getName()); } } } catch (Exception e) { System.err.println("文件上传失败!"); } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 上传文件夹 * * @param ftpClient * @param localDir 传输的源端目录 * @param serverDir 传输的目的端目录 */ public static void uploadDirectory(FTPClient ftpClient, String localDir, String serverDir) { File file = new File(localDir); try { serverDir = serverDir + file.getName() + "/"; boolean flag = ftpClient.makeDirectory(serverDir); System.out.println("[serverDir : " + serverDir + "][serverDir : " + serverDir + "][makeDirFlag: " + flag + "]"); } catch (IOException e) { e.printStackTrace(); System.err.println(serverDir + "目录创建失败!"); } File[] allFile = file.listFiles(); for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (!allFile[currentFile].isDirectory()) { uploadFile(ftpClient, allFile[currentFile].getPath(), serverDir); } } for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (allFile[currentFile].isDirectory()) { // 递归 uploadDirectory(ftpClient, allFile[currentFile].getPath(), serverDir); } } } /** * 文件下载 * * @param ftpClient FTP客户端 * @param serverDir 待下载的目录 * @param fileName 待下载的文件名 * @param localPath 下载到本地的路径 */ public static void downloadFile(FTPClient ftpClient, String serverDir, String fileName, String localPath) { OutputStream outputStream = null; String strFilePath = localPath + fileName; try { // 转移到FTP服务器目录至指定的目录下 boolean changeDir = ftpClient.changeWorkingDirectory(new String(serverDir.getBytes(encoding), "iso-8859-1")); System.out.println("改变工作目录: " + changeDir); if (changeDir) { // 获取文件列表 outputStream = new BufferedOutputStream(new FileOutputStream( strFilePath)); boolean result = ftpClient.retrieveFile(fileName, outputStream); if (result) { System.out.println("文件下载成功: " + strFilePath); } } } catch (IOException e) { e.printStackTrace(); System.err.println("文件下载失败!"); } finally { if (null != outputStream) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 下载文件夹 * * @param ftpClient * @param localDir 传输的源端目录 * @param serverDir 传输的目的端目录 */ public static void downLoadDirectory(FTPClient ftpClient, String localDir, String serverDir) { try { String fileName = new File(serverDir).getName(); localDir = localDir + fileName + "//"; boolean flag = new File(localDir).mkdirs(); System.out.println("[mkdirFlag: " + flag + "][localDir: " + localDir + "]"); FTPFile[] allFile = ftpClient.listFiles(serverDir); for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (!allFile[currentFile].isDirectory()) { downloadFile(ftpClient, serverDir, allFile[currentFile].getName(), localDir); } } for (int currentFile = 0; currentFile < allFile.length; currentFile++) { if (allFile[currentFile].isDirectory()) { String serverPath = serverDir + "/" + allFile[currentFile].getName(); downLoadDirectory(ftpClient, localDir, serverPath); } } } catch (IOException e) { e.printStackTrace(); System.err.println("下载文件夹失败!"); } } }
最新回复(0)