连接工具可用
java 连接ftp的方式
FtpConfiguration 配置文件
package com.goboo.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author Administrator
* @Classname SftpConfiguration
* @Description
* @Created by lsx
*/
@Data
@Component
@ConfigurationProperties(prefix="ftp")
public class FtpConfiguration {
/**
* FTP服务器IP地址
*/
private String host;
/**
* SFTP服务器端口
*/
private Integer port;
/**
* 用户
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 上传到文件服务器的那个目录
*/
private String uploadDir;
/**
* 连接超时时间,单位毫秒
*/
private Integer timeout;
/**
* 导入文件存放目录
*/
private String sourceDirectory;
/**
* 默认的
*/
private String cron;
}
package com.goboo.modules.job.utils;
import com.goboo.common.config.FtpConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
/**
* 基于JSch的Sftp工具类
* @author lsx
*/
@Slf4j
public class FtpUtil {
private FtpUtil() {
}
/**
* @Author lsx
* @param sftpConfiguration
* @param inputStream
* @param saveName
* @return boolean
*/
public static FTPClient upload(FtpConfiguration sftpConfiguration, InputStream inputStream, String saveName) {
boolean flag = false;
FTPClient ftpClient = new FTPClient();
if (connect(ftpClient, sftpConfiguration.getHost(), sftpConfiguration.getPort(), sftpConfiguration.getUsername(), sftpConfiguration.getPassword())) {
try {
//2 检查工作目录是否存在
if (ftpClient.changeWorkingDirectory(sftpConfiguration.getUploadDir())) {
// 3 检查是否上传成功
if (storeFile(ftpClient, saveName, inputStream)) {
flag = true;
// disconnect(ftpClient);
}
}
} catch (IOException e) {
log.error("工作目录不存在");
e.printStackTrace();
disconnect(ftpClient);
}
}
return ftpClient;
}
/**
* 断开连接
*
* @param ftpClient
* @throws Exception
*/
public static void disconnect(FTPClient ftpClient) {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
log.error("已关闭连接");
} catch (IOException e) {
log.error("没有关闭连接");
e.printStackTrace();
}
}
}
/**
* 测试是否能连接
*
* @param ftpClient
* @param hostname ip或域名地址
* @param port 端口
* @param username 用户名
* @param password 密码
* @return 返回真则能连接
*/
public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
boolean flag = false;
try {
//ftp初始化的一些参数
ftpClient.connect(hostname, port);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("UTF-8");
if (ftpClient.login(username, password)) {
log.info("连接ftp成功");
flag = true;
} else {
log.error("连接ftp失败,可能用户名或密码错误");
try {
disconnect(ftpClient);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
log.error("连接失败,可能ip或端口错误");
e.printStackTrace();
}
return flag;
}
/**
* 上传文件
*
* @param ftpClient
* @param saveName 全路径。如/home/public/a.txt
* @param fileInputStream 要上传的文件流
* @return
*/
public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
boolean flag = false;
try {
if (ftpClient.storeFile(saveName, fileInputStream)) {
flag = true;
log.error("上传成功");
}
} catch (IOException e) {
log.error("上传失败");
disconnect(ftpClient);
e.printStackTrace();
}
return flag;
}
}
上传文件调用工具类
FtpUtil.upload(sftpConfiguration, new FileInputStream(file), file.getName());
## Sftp 的连接方式
package com.dxn.utils;
import com.czinfo.framework.exception.ApplicationException;
import com.czinfo.framework.utils.SpringBeanFactory;
import com.dxn.config.BsnUriConfiguration;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Objects;
import java.util.Properties;
/**
* 基于JSch的Sftp工具类
*/
@Slf4j
public class SftpUtil {
/**
* Session
*/
private static Session session = null;
/**
* Channel
*/
private static ChannelSftp channel = null;
private static BsnUriConfiguration bsnUriConfiguration = SpringBeanFactory.getBean("bsnUriConfiguration");
/**
* 登陆SFTP服务器
*
* @return boolean
*/
public static boolean login() {
try {
JSch jsch = new JSch();
session = jsch.getSession(bsnUriConfiguration.getFtp().getUsername(),bsnUriConfiguration.getFtp().getHost(), bsnUriConfiguration.getFtp().getPort());
if (bsnUriConfiguration.getFtp().getPassword() != null) {
session.setPassword(bsnUriConfiguration.getFtp().getPassword());
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(bsnUriConfiguration.getFtp().getTimeout());
session.connect();
log.debug("sftp session connected");
log.debug("opening channel");
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
log.debug("connected successfully");
return true;
} catch (JSchException e) {
log.error("sftp login failed", e);
return false;
}
}
/**
* 登出sftp
*/
public static void logout() {
if (channel != null) {
channel.quit();
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
log.debug("logout successfully");
}
/**
* 单个文件上传 (sftp目录不存在则创建后上传)
* @param remoteFileName 远程文件名
* @return
*/
public String uploadFile(String remoteFileName, OutputStream outputStream) {
ByteArrayInputStream in = null;
try {
String remoteDir = bsnUriConfiguration.getFtp().getUploadDir();
//目录不存在则创建
createDir(remoteDir);
String remoteFilePath = remoteDir + "/" + remoteFileName;
//将outputStream转换成FileInputStream
in = ConvertUtil.parse(outputStream);
channel.put(in, remoteFilePath);
return remoteFilePath;
} catch (Exception e) {
log.error( e + "");
throw new ApplicationException(I18nDbUtils.getI18nValue("ftp.problem"));
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 单个文件上传 (sftp目录不存在则创建后上传)
*
* @param remoteFileName 远程文件名
* @param in
* @return
*/
public boolean uploadFile(InputStream in, String remoteFileName) {
try {
//目录不存在则创建后上传
createDir(bsnUriConfiguration.getFtp().getUploadDir());
channel.put(in, remoteFileName);
return true;
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量上传 (sftp目录不存在则创建后上传)
*
* @param localPath
* @param isDel 是否上传完成后删除 true-删除 false-不删除
* @return
*/
public static boolean batchUploadFile( String localPath, boolean isDel) {
try {
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
if (files[i].isFile()
&& !files[i].getName().contains("bak")) {
synchronized (localPath) {
/*if (uploadFile(files[i].getName(),
localPath, files[i].getName()) && isDel) {
deleteFile(localPath + files[i].getName());
}*/
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
channel.disconnect();
}
return false;
}
/**
* 单个文件下载 (应用目录不存在则创建后下载)
*
* @param remotePath
* @param remoteFileName
* @param localPath
* @param localFileName
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
try {
channel.cd(remotePath);
File file = new File(localPath + localFileName);
mkdirs(localPath + localFileName);
channel.get(remoteFileName, new FileOutputStream(file));
return true;
} catch (FileNotFoundException | SftpException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断目录存不存在,不存在则创建
*
* @param createpath
* @return
*/
public static boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
channel.cd(createpath);
log.info(createpath);
return true;
}
String[] pathArry = createpath.split("/");
StringBuilder filePath = new StringBuilder("/");
for (String path : pathArry) {
if ("".equals(path)) {
continue;
}
filePath.append(path).append("/");
createpath = filePath.toString();
if (isDirExist(createpath)) {
channel.cd(createpath);
} else {
channel.mkdir(createpath);
channel.cd(createpath);
}
}
channel.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public static boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = channel.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if ("no such file".equals(e.getMessage().toLowerCase())) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除应用服务器文件(用于应用服务器上传SFTP文件服务器完成后)
*
* @param filePath
* @return
*/
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
return file.delete();
}
/**
* 创建目录
*
* @param path
*/
public static void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
}
**
## 调用方式:
**
private void uploadFileFtp(List<DxnChainCode> ccList) throws ApplicationException{
//登陆SFTP服务器
boolean login = SftpUtil.login();
if(!login){
throw new ApplicationException(I18nDbUtils.getI18nValue("ftp.problem"));
}
//上传后的文件路径
new SftpUtil().uploadFile(dxnChainCode.getId() + ".zip", outputStream);
//退出sftp
SftpUtil.logout();
}
***