springboot连接ftp服务器

1.引入pom文件

                <!-- ftp -->
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>3.6</version>
		</dependency>

2.配置application.properties文件

ftp.client.username="ftp";
ftp.client.password="****"
ftp.client.host="127.0.0.0"
ftp.client.port="22"

3.配置ftp连接类FtpConnect

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Component
public class FtpConnect {
	private static Logger logger = LoggerFactory.getLogger(FtpConnect.class);
	
	// FTP 登录用户名
	@Value("${ftp.client.username}")
	private String userName;
	// FTP 登录密码
	@Value("${ftp.client.password}")
	private String pwd;
	// FTP 服务器地址IP地址
	@Value("${ftp.client.host}")
	private String host;
	// FTP 端口
	@Value("${ftp.client.port}")
	private int port;

	/**
	 * 连接ftp
	 * 
	 * @return
	 * @throws Exception
	 */
	public FTPClient getFTPClient() {
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient = new FTPClient();
			logger.info("地址:" + host + "-" + port);
			ftpClient.connect(host, port);// 连接FTP服务器
			logger.info("用户名:" + userName);
			ftpClient.login(userName, pwd);// 登陆FTP服务器
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				logger.info("未连接到FTP,用户名或密码错误。");
				ftpClient.disconnect();
			} else {
				logger.info("FTP连接成功。");
			}
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置二进制传输
		} catch (SocketException e) {
			logger.error("连接ftp失败!");
			logger.info("FTP的IP地址可能错误,请正确配置。");
		} catch (IOException e) {
			logger.error("连接ftp失败!");
			logger.info("FTP的端口错误,请正确配置。");
		}
		return ftpClient;
	}

	/**
	 * 关闭连接
	 * 
	 * @param ftpClient
	 */
	public void close(FTPClient ftpClient) {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (IOException e) {
			logger.error("ftp连接关闭失败!");
		}
	}
}

4.创建ftp工具类 下载ftp服务器文件到本地FtpUtil

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class FtpUtil {

	private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);
	public static final String DIRSPLIT = "/";

	public static File downloadFile(FTPClient ftpClient, String targetPath, String filetype) throws Exception {

		OutputStream outputStream = null;
		try {
			File directory = new File(".");
			String path = null;
			path = directory.getCanonicalPath();// 获取当前路径
			logger.info("当前路径" + path);
			path = path + DIRSPLIT + filetype;
			logger.info("目录路径" + path);
			File fileDire = new File(path);
			if (!fileDire.exists() && !fileDire.isDirectory()) {
				fileDire.mkdirs();
			}
			path = path + DIRSPLIT + targetPath.substring(targetPath.lastIndexOf("/") + 1);
			logger.info("文件路径" + path);
			File file = new File(path);
			if (!file.exists()) {
				if (!file.createNewFile()) {
					logger.info("创建文件失败!");
					return null;
				}

			}
			outputStream = new FileOutputStream(file);
			ftpClient.retrieveFile(targetPath, outputStream);
			logger.info("Download file success. TargetPath: {}", targetPath);
			return file;
		} catch (Exception e) {
			logger.error("Download file failure. TargetPath: {}", targetPath);
			throw new Exception("Download File failure");
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param pathname
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteFile(File file) {
		boolean result = false;
		if (file.exists()) {
			if (file.delete()) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 处理文件名绝对路径
	 * 
	 * @param filePath
	 * @param fileName
	 * @return P:/temp/1.txt 或者 p:/temp/x
	 */
	public static String pasreFilePath(String filePath, String fileName) {
		StringBuffer sb = new StringBuffer();
		if (filePath.endsWith("/") || filePath.endsWith("\\")) {
			sb.append(filePath).append(fileName);
		} else {
			sb.append(filePath.replaceAll("\\\\", "/")).append("/").append(fileName);
		}
		return sb.toString();
	}

	/**
	 * 获取今天日期 - 数字格式
	 * 
	 * @return yyyyMMdd
	 */
	public static String getCurrentday() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, 0);
		return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
	}

	/**
	 * 获取昨天日期 - 数字格式
	 * 
	 * @return yyyyMMdd
	 */
	public static String getYesterday() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
	}
}

5.创建一个定时任务获取ftp服务器文件

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
@EnableScheduling // 通过@EnableScheduling注解开启对计划任务的支持
public class TaskSchedule {
	private static Logger logger = LoggerFactory.getLogger(TaskSchedule.class);

	@Autowired
	private FtpConnect connect;
	private long sleepTime = 60000;
	private long total = 10;
	private long num = 0;
	public static final String UNDERLINE = "_";
	public static final String preFileName = ".areq";
	

	@Scheduled(cron = "0 0 0/2 * * ?")
	public String importSPserviceinfo() {
		String readSPservicePathDay = "/**/"+ FtpUtil.getCurrentday() + "/";
		logger.info("文件路径:" + readSPservicePathDay);
		String info = "xxx";//文件关键字

		// 获取远程目录下的文件到容器
		List<File> files = sftpGet(info, readSPservicePathDay);
		return "0000";
	}

	/**
	 * 获取远程目录下的文件到容器
	 */
	public List<File> sftpGet(String filetype, String path) {
		FTPClient ftpClient = null;
		// 获取今天日期
		String today = FtpUtil.getCurrentday();
		FTPFile[] ftpFiles = null;
		List<File> files = new ArrayList<File>();
		String filetypeDate = filetype + UNDERLINE + today;
		try {
			ftpClient = connect.getFTPClient();
			// 跳转到指定目录
			ftpClient.changeWorkingDirectory(path);
		} catch (Exception e1) {
			logger.error("ftp连接异常");
		}
		try {
                        //ftp client告诉ftp server开通一个端口来传输数据
			ftpClient.enterLocalPassiveMode();
			logger.info("获得指定目录下的文件夹和文件信息");
			ftpFiles = ftpClient.listFiles();
			for (int i = 0; i < ftpFiles.length; i++) {
				FTPFile ftpfile = ftpFiles[i];
				String name = ftpfile.getName();
				if (".".equals(name) || "..".equals(name) || ftpfile.isDirectory()) {
					continue;
				}
				if (name.startsWith(filetypeDate) && name.endsWith(preFileName)) {
					logger.info("获取到目录下文件名:" + name);
					String sftpRemoteAbsolutePath = FtpUtil.pasreFilePath(path, name); // 远程服务器
					File file = FtpUtil.downloadFile(ftpClient, sftpRemoteAbsolutePath, filetype);
					files.add(file);
				}
			}
			if (files.isEmpty()) {
				throw new Exception();
			}
		} catch (Exception e) {
			logger.error(" sftpGet  error");
			logger.error("次数" + num);
			if (num == total) {
				num = 0;
				throw new RuntimeException(e);
			}
			try {
				num += 1;
				Thread.sleep(sleepTime);
				importSPserviceinfo();
			} catch (InterruptedException e1) {
				logger.error("获取文件失败");
				Thread.currentThread().interrupt();
			}
		} finally {
			connect.close(ftpClient);
		}
		return files;
	}
}

 

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中搭建FTP服务器,可以使用Apache Commons Net库,该库提供了FTP服务器实现的支持。下面是一个简单的示例: 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.7.2</version> </dependency> ``` 2. 编写FTP服务器配置 在Spring Boot的配置类中,添加以下配置: ```java @Configuration public class FtpServerConfig { @Value("${ftp.server.port}") private int port; @Value("${ftp.server.user}") private String user; @Value("${ftp.server.password}") private String password; @Value("${ftp.server.homeDirectory}") private String homeDirectory; @Bean(initMethod = "start", destroyMethod = "stop") public FtpServerFactoryBean ftpServerFactoryBean() { FtpServerFactoryBean factory = new FtpServerFactoryBean(); factory.setPort(port); // 添加用户 UserManager userManager = new BaseUserManager(); User userObj = new User(); userObj.setName(user); userObj.setPassword(password); userObj.setHomeDirectory(homeDirectory); List<Authority> authorities = new ArrayList<>(); authorities.add(new WritePermission()); userObj.setAuthorities(authorities); try { userManager.save(userObj); } catch (FtpException e) { throw new RuntimeException("Failed to create user", e); } factory.setUserManager(userManager); // 添加文件系统 FileSystemFactory fileSystemFactory = new NativeFileSystemFactory(); factory.setFileSystem(fileSystemFactory); return factory; } } ``` 3. 配置文件 在application.properties或application.yml文件中添加FTP服务器的相关属性: ```properties ftp.server.port=21 ftp.server.user=admin ftp.server.password=password ftp.server.homeDirectory=/ftp ``` 4. 启动FTP服务器 在Spring Boot应用程序启动后,FTP服务器将自动启动。您可以使用任何FTP客户端连接到服务器,并使用配置的用户名和密码进行身份验证,然后上传、下载和管理文件。 以上是一个简单的示例,您可以根据自己的需求进行更改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值