实现sftp 上传下载需要引入jsch-0.1.54.jar
jsch 包地址:链接: https://pan.baidu.com/s/1eOUu0CXE-iIaWB8IuT5AkA 提取码: 6src
maven 配置
代码:
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
import java.util.Properties;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class SftpService {
/** Session */
static Session sshSession = null;
/** Channel */
private ChannelSftp channel ;
/** SFTP服务器IP地址 */
private String host;
/** SFTP服务器端口 */
private int port;
/** 连接超时时间,单位毫秒 */
private int timeout=1000;
/** 用户名 */
private String username;
/** 密码 */
private String password;
private String directory;
private String uploadFile;
private String saveFile;
/**
* 上传文件
* @param directory SFTP服务器目录
* @param uploadFile 上传文件路径
* @param filename 文件名称
* @return boolean
*/
public Result upload(Map param) {
Map params = JsonHelper.objectToJsonToMap(param.get("params"));
String validateParamsMsg = DataUtil.validateParam(params,new String[]{"filters"});
if(!code.equals(validateParamsMsg)){
return Result.fail(Result.DEFUALTPARAM,"缺少必须的请求参数");
}
List<Map> filtersList = (List<Map>)params.get("filters");
for(Map filter:filtersList){
validateParamsMsg = DataUtil.validateParam(filter,new String[]{"host","port","username","password","directory","uploadFile","filename"});
if(!code.equals(validateParamsMsg)){
return Result.fail(Result.DEFUALTPARAM,"缺少必须的请求参数");
}
String host = (String)filter.get("host");
if(null==host||"".equals(host)){
return Result.fail("服务器ip为空");
}
String port = (String)filter.get("port");
if(null==port||"".equals(port)){
return Result.fail("服务器端口号为空");
}
String username = (String)filter.get("username");
if(null==username||"".equals(username)){
return Result.fail("服务器用户名为空");
}
String password = (String)filter.get("password");
if(null==password||"".equals(password)){
return Result.fail("服务器密码为空");
}
String directory = (String)filter.get("directory");
if(null==directory||"".equals(directory)){
return Result.fail("服务器路径为空");
}
String file = filter.get("uploadFile").toString();
if(null==file||"".equals(file)){
return Result.fail("未获取文件流对象");
}
String filename = (String) filter.get("filename");
if(null==filename||"".equals(filename)){
return Result.fail("文件名称为空");
}
ChannelSftp ftp = getConnectIP(host, port, username, password);
if (uploadFile(directory, file, ftp,filename)) {
return Result.success("true");
}else {
return Result.success("上传失败");
}
}
return null;
}
/**
* 下载文件
* @param directory SFTP服务器目录
* @param downloadFile 下载文件名称
* @param saveFile 下载到本地路径
* @return boolean
*/
public Result download(Map param) {
Map params = JsonHelper.objectToJsonToMap(param.get("params"));
String validateParamsMsg = DataUtil.validateParam(params,new String[]{"filters"});
if(!code.equals(validateParamsMsg)){
return Result.fail(Result.DEFUALTPARAM,"缺少必须的请求参数");
}
List<Map> filtersList = (List<Map>)params.get("filters");
for(Map filter:filtersList){
validateParamsMsg = DataUtil.validateParam(filter,new String[]{"host","port","username","password","directory","downloadFile","saveFile"});
if(!code.equals(validateParamsMsg)){
return Result.fail(Result.DEFUALTPARAM,"缺少必须的请求参数");
}
String host = (String)filter.get("host");
if(null==host||"".equals(host)){
return Result.fail("服务器ip为空");
}
String port = (String)filter.get("port");
if(null==port||"".equals(port)){
return Result.fail("服务器端口号为空");
}
String username = (String)filter.get("username");
if(null==username||"".equals(username)){
return Result.fail("服务器用户名为空");
}
String password = (String)filter.get("password");
if(null==password||"".equals(password)){
return Result.fail("服务器密码为空");
}
String directory = (String)filter.get("directory");
if(null==directory||"".equals(directory)){
return Result.fail("服务器路径为空");
}
String downloadFile = (String)filter.get("downloadFile");
if(null==downloadFile||"".equals(downloadFile)){
return Result.fail("下载文件名称为空");
}
String saveFile = (String)filter.get("saveFile");
if(null==saveFile||"".equals(saveFile)){
return Result.fail("本地路径为空");
}
ChannelSftp ftp = getConnectIP(host, port, username, password);
if (downloadFile(directory,downloadFile,saveFile,ftp)) {
return Result.success("true");
}else {
return Result.success("下载失败");
}
}
return null;
}
/**
* 上传文件
* @param directory SFTP服务器目录
* @param filename 服务器上保存的文件名
* @param sftp
* @return boolean
*/
public boolean uploadFile(String directory, String file, ChannelSftp sftp,String filename) {
try {
try {
sftp.cd(directory);
} catch (SftpException e) {
try {
sftp.mkdir(directory);//目录不存在就创建
sftp.cd(directory);
} catch (SftpException e1) {
throw new RuntimeException("sftp创建文件路径失败" + directory);
}
}
ByteArrayInputStream input = new ByteArrayInputStream(file.getBytes());
sftp.put(input, filename);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
/**
* 下载文件
* @param directory SFTP服务器目录
* @param downloadFile 服务器上需要下载的文件名
* @param saveFile 本地保存文件名
* @param sftp
* @return boolean
*/
public boolean downloadFile(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
OutputStream output = null;
try {
File localDirFile = new File(saveFile);
// 判断本地目录是否存在,不存在需要新建各级目录
if (!localDirFile.exists()) {
localDirFile.mkdirs();
}
sftp.cd(directory);
//File file = new File(saveFile);
output = new FileOutputStream(new File(saveFile.concat(File.separator).concat(downloadFile)));
sftp.get(downloadFile, output);
if (logger.isInfoEnabled()) {
logger.info("文件下载成功");
}
return true;
} catch (Exception e) {
e.printStackTrace();
logger.info("文件下载异常");
return false;
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
/**
* 获取ChannelSftp
*
* @param host
* 主机
* @param sOnlineSftpPort
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {
int port = 0;
if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {
port = Integer.parseInt(sOnlineSftpPort);
}
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
}
}
测试类:
import java.io.;
import java.util.;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) throws Exception {
SftpService sftpService=new SftpService();
List<Map<String,Object>> filters=new ArrayList<Map<String,Object>>();
JSONObject params=new JSONObject();
File file = new File("D:\\upload\\test.txt");
InputStream input = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Map<String,Object> filter=new HashMap<String,Object>();
filter.put("host","服务器ip");
filter.put("port","端口");
filter.put("username","用户");
filter.put("password","密码");
filter.put("directory","上传路径");
filter.put("uploadFile",sb);
filter.put("filename","文件名");
filters.add(filter);
params.put("filters",filters);
JSONObject param=new JSONObject();
param.put("params",params);
sftpService.upload(param);