工具类分享,SftpUtils sftp上传下载文件
工具类代码:
package com.kanq.util;
import com.jcraft.jsch.*;
import com.kanq.bdc_gxjh.FTPConfig;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class SftpUtils {
public static void main(String[] args) throws Exception {
// 1
File file = new File("E:\\2.xlsx");
SftpUtils.uploadFile("/usr/local", "/testfile/", "test.xlsx", file);
// 2
SftpUtils.downloadFile("", "", "", 22, null, "/usr/local/testfile/", "test.csv", "/Users/ao/Desktop/test.csv");
// 3
SftpUtils.deleteFile("", "", "", 22, null, "/usr/local/testfile/", "test.xlsx");
// 4
Vector<?> fileList = SftpUtils.getFileList("", "", "", 22, null, "/usr/local/testfile/");
}
/**
* @param basePath 根路径
* @param filePath 文件路径(加上根路径)
* @param filename 文件名
* @param file 文件流
* @Description: 上传文件
*/
public static void uploadFile(String basePath, String filePath, String filename, File file) {
try {
//获取sftp配置信息
List<String> FTPlist = FTPConfig.INSTANCE.getSourceLocation();
String host = FTPlist.get(1);
int port = Integer.parseInt(FTPlist.get(2));
String userName = FTPlist.get(3);
String password = FTPlist.get(4);
System.out.println("sftp ip:"+host+",端口:"+port+",用户名:"+userName+",密码:"+password);
Session session = null;
ChannelSftp sftp = null;
// 连接sftp服务器
try {
JSch jsch = new JSch();
session = jsch.getSession(userName, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
System.out.println("sftp 连接超时报错");
e.printStackTrace();
}
// 将输入流的数据上传到sftp作为文件
try {
System.out.println("sftp 附件路径:"+filePath);
// sftp.cd(basePath);
sftp.cd("/"+filePath);
} catch (SftpException e) {
//目录不存在,则创建文件夹
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) {
continue;
}
tempPath += "/" + dir;
try {
sftp.cd(tempPath);
} catch (SftpException ex) {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
}
}
}
InputStream in = new FileInputStream(file);
//上传文件
sftp.put(in, filename);
//关闭连接 server
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
//关闭连接 server
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
} catch (Exception e) {
System.out.println("sftp 程序异常");
e.printStackTrace();
}
}
/**
* @param userName 用户名
* @param password 密码
* @param host ip
* @param port 端口
* @param privateKey 秘钥
* @param directory 文件路径
* @param downloadFile 文件名
* @param saveFile 存在本地的路径
* @Author: jinhaoxun
* @Description: 下载文件
* @Date: 2020/1/16 21:22
* @Return: void
* @Throws: Exception
*/
public static void downloadFile(String userName, String password, String host, int port, String privateKey, String directory,
String downloadFile, String saveFile) throws Exception {
Session session = null;
ChannelSftp sftp = null;
// 连接sftp服务器
try {
JSch jsch = new JSch();
if (privateKey != null) {
// 设置私钥
jsch.addIdentity(privateKey);
}
session = jsch.getSession(userName, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}
/**
* @param userName 用户名
* @param password 密码
* @param host ip
* @param port 端口
* @param privateKey 秘钥
* @param directory 文件路径
* @param downloadFile 文件名
* @Author: jinhaoxun
* @Description: 下载文件
* @Date: 2020/1/16 21:21
* @Return: byte[]
* @Throws: Exception
*/
public static byte[] downloadFile(String userName, String password, String host, int port, String privateKey,
String directory, String downloadFile) throws Exception {
Session session = null;
ChannelSftp sftp = null;
// 连接sftp服务器
try {
JSch jsch = new JSch();
if (privateKey != null) {
// 设置私钥
jsch.addIdentity(privateKey);
}
session = jsch.getSession(userName, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
return fileData;
}
/**
* @param userName 用户名
* @param password 密码
* @param host ip
* @param port 端口
* @param privateKey 秘钥
* @param directory 文件路径
* @param deleteFile 文件名
* @Author: jinhaoxun
* @Description: 删除文件
* @Date: 2020/1/16 21:24
* @Return: void
* @Throws: Exception
*/
public static void deleteFile(String userName, String password, String host, int port, String privateKey,
String directory, String deleteFile) throws Exception {
Session session = null;
ChannelSftp sftp = null;
// 连接sftp服务器
try {
JSch jsch = new JSch();
if (privateKey != null) {
// 设置私钥
jsch.addIdentity(privateKey);
}
session = jsch.getSession(userName, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* @param userName 用户名
* @param password 密码
* @param host ip
* @param port 端口
* @param privateKey 秘钥
* @param directory 要列出的目录
* @Author: jinhaoxun
* @Description: 列出目录下的文件
* @Date: 2020/1/16 21:25
* @Return: java.util.Vector<?>
* @Throws: Exception
*/
public static Vector<?> getFileList(String userName, String password, String host, int port, String privateKey,
String directory) throws Exception {
Session session = null;
ChannelSftp sftp = null;
// 连接sftp服务器
try {
JSch jsch = new JSch();
if (privateKey != null) {
// 设置私钥
jsch.addIdentity(privateKey);
}
session = jsch.getSession(userName, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
return sftp.ls(directory);
}
}
上面工具类涉及的配置文件FTPConfig,可以使用yml配置文件更简洁 :
package com.kanq.bdc_gxjh;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public enum FTPConfig {
INSTANCE;
private final Properties props;
{
String relativePath = ConfigUtils.getResourceNameForConfigFile("SFTPServer.properties");
props = new Properties();
try {
// new FileInputStream(absolutePath);
InputStream in = FTPConfig.class.getClassLoader().getResourceAsStream(relativePath);
props.load(in);
} catch (IOException e) {
LoggerFactory.getLogger(CheckDbConfig.class).warn(
ConfigUtils.ConfigFileNameContainer.FTPSERVER + "配置文件加载失败!!!"+ e.toString());
}
}
public List<String> getSourceLocation() {
String sourceLocation = props.getProperty("ftp.Location");
String ip=props.getProperty("ftp.ip");
String port=props.getProperty("ftp.port");
String username=props.getProperty("ftp.userName");
String pawd=props.getProperty("ftp.passWord");
return Lists.newArrayList(sourceLocation,ip,port,username,pawd);
}
}
配置文件SFTPServer.properties
#文件本地存放路径
ftp.Location=D:\\download\\
ftp.ip=192.168.0.36
ftp.port=21
ftp.userName=administrator
ftp.passWord=asdfghjkl;'
Maven 配置:
我们需要将 jsch 依赖添加到我们的 pom.xml 中:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
好了,分享到这里结束了,希望帮助到大家!