1.导入maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
SftpUtil 工具类
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
public class SftpUtil {
private Logger logger = LogManager.getLogger(SftpUtil.class);
private ChannelSftp sftp;
private Session session;
private String username;
private String password;
private String privateKey;
private String host;
private int port;
public SftpUtil(String username, String password, String host, int port){
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public SftpUtil(String username, String privateKey, int port, String host){
this.username = username;
this.privateKey = privateKey;
this.host = host;
this.port = port;
}
public void login(){
JSch jsch = new JSch();
try{
if(privateKey != null){
jsch.addIdentity(privateKey);
}
session = jsch.getSession(username,host,port);
if(password != null){
session.setPassword(password);
}
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
logger.info("sftp server connect success !!");
}catch (JSchException e){
logger.error("SFTP服务器连接异常!!", e);
}
}
public void logout(){
if(sftp != null){
if(sftp.isConnected()){
sftp.disconnect();
logger.info("sftp is close already");
}
}
if(session != null){
if(session.isConnected()){
session.disconnect();
logger.info("session is close already");
}
}
}
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
long start = System.currentTimeMillis();
try{
if(sftp.ls(directory) == null){
sftp.mkdir(directory);
}
sftp.cd(directory);
}catch (SftpException e){
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
logger.info("文件上传成功!! 耗时:{}ms",(System.currentTimeMillis() - start));
}
public void upload(String directory, String uploadFileUrl){
File file = new File(uploadFileUrl);
try{
upload(directory, file.getName(), new FileInputStream(file));
}catch (FileNotFoundException | SftpException e){
logger.error("上传文件异常!", e);
}
}
public void upload(String directory, String sftpFileName, byte[] bytes){
try{
upload(directory, sftpFileName, new ByteArrayInputStream(bytes));
}catch (SftpException e){
logger.error("上传文件异常!", e);
}
}
public void upload(String directory, String sftpFileName, String dataStr, String charsetName){
try{
upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
}catch (UnsupportedEncodingException | SftpException e){
logger.error("上传文件异常!", e);
}
}
public void download(String directory, String downloadFile, String saveFile){
try{
if(directory != null && !"".equals(directory)){
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}catch (SftpException | FileNotFoundException e){
logger.error("文件下载异常!", e);
}
}
public byte[] download(String directory, String downloadFile){
try{
if(directory != null && !"".equals(directory)){
sftp.cd(directory);
}
InputStream inputStream = sftp.get(downloadFile);
return IOUtils.toByteArray(inputStream);
}catch (SftpException | IOException e){
logger.error("文件下载异常!", e);
}
return null;
}
public InputStream downloadStream(String directory, String downloadFile){
try{
if(directory != null && !"".equals(directory)){
sftp.cd(directory);
}
return sftp.get(downloadFile);
}catch (SftpException e){
logger.error("文件下载异常!", e);
}
return null;
}
public void delete(String directory, String deleteFileName){
try{
sftp.cd(directory);
sftp.rm(deleteFileName);
}catch (SftpException e){
logger.error("文件删除异常!", e);
}
}
public void delete(String directory){
Vector vector = listFiles(directory);
vector.remove(0);
vector.remove(0);
for(Object v : vector){
ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry)v;
try{
sftp.cd(directory);
sftp.rm(lsEntry.getFilename());
}catch (SftpException e){
logger.error("文件删除异常!", e);
}
}
}
public Vector<?> listFiles(String directory){
try{
if(isDirExist(directory)){
Vector<?> vector = sftp.ls(directory);
vector.remove(0);
vector.remove(0);
return vector;
}
}catch (SftpException e){
logger.error("获取文件夹信息异常!", e);
}
return null;
}
public boolean booleanUrl(String directory){
try{
if(sftp.ls(directory) == null){
return false;
}
}catch (Exception e){
logger.error("检测文件夹异常!", e);
}
return true;
}
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
} catch (SftpException e) {
logger.error("目录创建异常!", e);
return false;
}
return true;
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = this.sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public void mkdirs(String path){
File file = new File(path);
String fs = file.getParent();
file = new File(fs);
if(!file.exists()){
file.mkdirs();
}
}
public boolean isExist(String path,ChannelSftp sftp){
boolean isExist=false;
try {
sftp.lstat(path);
isExist = true;
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isExist = false;
}
}
return isExist;
}
}
3 测试
public static void main(String[] args) throws SftpException, NoSuchFieldException, IllegalAccessException {
String username = "root";
String password = "root";
String host = "192.168.28.211";
int port = 22;
SftpUtil sftpUtil = new SftpUtil(username,password,host,port);
sftpUtil.login();
Vector<?> objects = sftpUtil.listFiles("/root/mytest/");
}