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;
	}
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页