SpringBoot-FTP操作
@Slf4j
@Component
public class FtpUtil implements CommandLineRunner {
private static int ftpPort = 21;
private static String ftpHost = "192.168.0.117";
private static String ftpUsername = "zht";
private static String ftpPassword = "123456";
@Autowired(required = false)
private BaseSysParamService baseSysParamService;
public FTPClient ftpClient = null;
public boolean trayAgeain = false;
@Qualifier("otherDateBaseExecutor")
@Autowired
private TaskExecutor taskExecutor;
@Override
public void run(String... args) throws Exception {
CompletableFuture.runAsync(() ->{
setParam();
getFtpClient();
}, taskExecutor);
}
public void setParam() {
CompletableFuture.runAsync(() ->{
String otherFtpServer = baseSysParamService.getValByName("pers.otherFtpServer");
if (StringUtils.isNotEmpty(otherFtpServer)) {
String[] serverPort = otherFtpServer.split(":");
if (serverPort.length >= 2) {
ftpPort = Optional.ofNullable(serverPort[1]).filter(StringUtils::isNotEmpty).map(Integer::parseInt).orElse(ftpPort);
ftpHost = Optional.ofNullable(serverPort[0]).filter(StringUtils::isNotEmpty).orElse(ftpHost);
}
}
String otherFtpUser = baseSysParamService.getValByName("pers.otherFtpUser");
ftpUsername = Optional.ofNullable(otherFtpUser).filter(StringUtils::isNotEmpty).orElse(ftpUsername);
String otherFtpPass = baseSysParamService.getValByName("pers.otherFtpPass");
ftpPassword = Optional.ofNullable(otherFtpPass).filter(StringUtils::isNotEmpty).orElse(ftpPassword);
}, taskExecutor);
}
public FTPClient initFtpClient() {
close();
try {
ftpClient = new FTPClient();
ftpClient.setConnectTimeout(1000 * 30);
ftpClient.setControlEncoding("utf-8");
ftpClient.setDefaultPort(ftpPort);
ftpClient.connect(ftpHost, ftpPort);
ftpClient.login(ftpUsername, ftpPassword);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
close();
log.error("未连接到FTP,用户名或密码错误!");
OtherFtpServiceImpl.addMessage("未连接到FTP,用户名或密码错误!");
return null;
} else {
log.info("FTP连接成功!");
return ftpClient;
}
} catch (SocketException socketException) {
log.error("FTP的IP地址可能错误,请正确配置!");
OtherFtpServiceImpl.addMessage("FTP的IP地址可能错误,请正确配置!");
return null;
} catch (IOException ioException) {
ioException.printStackTrace();
log.error("FTP的端口错误,请正确配置!");
OtherFtpServiceImpl.addMessage("FTP的端口错误,请正确配置!");
return null;
}
}
public void close() {
if (ObjectUtils.isNotEmpty(ftpClient)) {
try {
ftpClient.disconnect();
ftpClient = null;
} catch (IOException e) {
e.printStackTrace();
log.info("关闭ftp异常");
}
}
}
public FTPClient getFtpClient() {
if (ObjectUtils.isEmpty(ftpClient) || !ftpClient.isConnected() || !FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
initFtpClient();
if (ObjectUtils.isEmpty(ftpClient)) {
CompletableFuture.runAsync(this::tryGetFtpClient, taskExecutor);
}
}
return ftpClient;
}
private synchronized void tryGetFtpClient() {
if (!trayAgeain) {
trayAgeain = true;
int max = 4;
int count = 0;
while (count < max) {
initFtpClient();
if (ObjectUtils.isNotEmpty(ftpClient) && ftpClient.isConnected()) {
break;
}
try {
log.info("连接ftp失败,将在10s后进行第 {} 次重试!", count);
OtherFtpServiceImpl.addMessage("连接ftp失败,将在10s后进行第 ").append(count).append(" 次重试!");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
trayAgeain = false;
}
}
public static void main(String[] args) {
OtherFtpService otherFtpService = new OtherFtpServiceImpl();
otherFtpService.readPerFile("test.txt", "/test");
}
public void logout() {
try {
if (ObjectUtils.isNotEmpty(ftpClient)) {
ftpClient.logout();
}
} catch (IOException e) {
log.info("登录退出失败!{}", e.getMessage());
e.printStackTrace();
}
}
public void closeInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭流失败 -------- {}", e.getMessage());
}
}
}
public FTPClient changeWorkingDirectory(String directory) {
try {
getFtpClient();
if (ObjectUtils.isNotEmpty(ftpClient)) {
boolean flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
log.info("进入文件夹" + directory + " 成功!");
} else {
log.info("进入文件夹" + directory + " 失败!");
OtherFtpServiceImpl.addMessage("进入文件夹" + directory + " 失败!");
}
}
} catch (IOException e) {
log.info("改变ftp目录失败!{}", e.getMessage());
OtherFtpServiceImpl.addMessage("改变ftp目录失败!" + e.getMessage());
CompletableFuture.runAsync(this::tryGetFtpClient, taskExecutor);
}
return ftpClient;
}
public String readFileToBase64(String remoteFileName, String remoteDir) {
String base64 = "";
InputStream inputStream = null;
try {
FTPClient ftpClient = changeWorkingDirectory(remoteDir);
if (ObjectUtils.isEmpty(ftpClient)) {
return null;
}
FTPFile[] ftpFiles = ftpClient.listFiles(remoteDir);
boolean flag = false;
for (FTPFile ftpFile : ftpFiles) {
String name = new String(ftpFile.getName().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
if (remoteFileName.equals(name)) {
flag = true;
break;
}
}
if (!flag) {
log.error("目录:{} 下没有 {}", remoteDir, remoteFileName);
OtherFtpServiceImpl.addMessage("目录:").append(remoteDir).append(" 下没有 ").append(remoteFileName);
OtherFtpServiceImpl.addDeptMessage("目录:", true).append(remoteDir).append(" 下没有 ").append(remoteFileName);
return null;
}
String filePath = remoteDir + File.separator +remoteFileName;
inputStream = ftpClient.retrieveFileStream(filePath);
if (ObjectUtils.isNotEmpty(inputStream)) {
Thread.sleep(1000);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
base64 = Base64Util.encode(bytes);
log.info("读取文件 {} 成功!", remoteFileName);
}else {
log.info("读取文件 {} 失败!path: {}", remoteFileName, filePath);
OtherFtpServiceImpl.addMessage("读取文件 ").append(remoteFileName).append(" 失败!path: ").append(filePath);
}
} catch (IOException | InterruptedException e) {
log.error("读取文件失败 ----->>> {}", e.getMessage());
OtherFtpServiceImpl.addMessage("读取文件 ").append(remoteFileName).append(" 失败!");
return null;
} finally {
closeInputStream(inputStream);
}
return base64;
}
public boolean uploadFile(InputStream inputStream, String originName, String remoteDir) {
try {
FTPClient ftpClient = changeWorkingDirectory(remoteDir);
if (ObjectUtils.isEmpty(ftpClient)) {
return false;
}
boolean isSuccess = ftpClient.storeFile(originName, inputStream);
if (isSuccess) {
log.info("{}---》上传成功!", originName);
} else {
log.info("{}---》上传失败!", originName);
}
return isSuccess;
} catch (IOException e) {
log.info("{}---》上传失败!", originName);
return false;
}
}
public void download(String remoteDir, String remoteFileName, OutputStream outputStream) {
InputStream inputStream = null;
try {
FTPClient ftpClient = changeWorkingDirectory(remoteDir);
FTPFile[] ftpFiles = ftpClient.listFiles();
if (ftpFiles != null && ftpFiles.length > 0) {
for (FTPFile ftpFile : ftpFiles) {
if (StringUtils.equals(ftpFile.getName(), remoteFileName)) {
ftpClient.retrieveFile(ftpFile.getName(), outputStream);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void deleteFile(String remoteDir, String fileName) {
FTPClient ftpClient = changeWorkingDirectory(remoteDir);
if (ObjectUtils.isNotEmpty(ftpClient)) {
try {
ftpClient.deleteFile(fileName);
} catch (IOException e) {
e.printStackTrace();
log.info("删除路径 {} 下文件 {} 失败!", remoteDir, fileName);
}
}
}
}