java使用Jsch组件链接资源上传下载文件
依赖:jsch-0.1.55.jar
package com.zxl.demo.sftp;
import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
@Component
public class SftpClientUtil {
public static Session session = null;
public static Channel channel = null;
private static JSch jsch;
private static ChannelSftp sftp;
public static void main(String[] args) {
sftp = jschConnect("test","test","127.0.0.1",22);
putFileEditDir("D:\\liang\\电子合同.pdf","/home/liang/files/电子合同.pdf");
getFileToFolder("D:\\liang\\电子合同1.pdf","/home/liang/files/电子合同.pdf");
}
private static ChannelSftp jschConnect(String userName,String pwd, String IP,int port) {
try {
jsch = new JSch();
session = jsch.getSession(userName, IP);
session.setPassword(pwd);
session.setPort(port);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.setTimeout(3000);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
System.out.println("链接成功");
} catch (JSchException e) {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
System.out.println("sftp链接异常:" + e.getMessage());
}
return (ChannelSftp) channel;
}
public static void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
public static boolean putFileEditDir(String localPath, String sftpPath) {
boolean result = false;
try {
System.out.println("=====putFileEditDir=====start");
System.out.println("文件保存路径:" + sftpPath);
if (!lstat(sftp,sftpPath)){
sftp.put(new FileInputStream(new File(localPath)), sftpPath);
closeChannel();
System.out.println("上传文件成功");
}
System.out.println("=====putFileEditDir=====end");
result = true;
} catch (Exception e) {
System.out.println("sftp上传文件异常:{}"+e.getMessage());
return result;
}
return result;
}
public static boolean getFileToFolder(String localPath, String sftpPath) {
System.out.println("=====getFileToFolder=====start");
boolean result = false;
try {
if (lstat(sftp,sftpPath)){
System.out.println("sftp服务文件路径:" + sftpPath);
System.out.println("网盘文件保存路径:" + localPath);
sftp.get(sftpPath, new FileOutputStream(new File(localPath)));
System.out.println("下载成功!删除sftp服务器文件{}:" + sftpPath);
sftp.rm(sftpPath);
}
closeChannel();
result = true;
} catch (Exception e) {
System.out.println("sftp下载文件异常或文件不存在:{}"+ e.getMessage());
return false;
}
System.out.println("=====getFileToFolder=====end");
return result;
}
private static boolean lstat(ChannelSftp sftp, String sftpFilePath){
try {
SftpATTRS lstat = sftp.lstat(sftpFilePath);
if (lstat == null){
System.out.println("{}文件不存在!不做处理"+sftpFilePath);
return false;
}
System.out.println("{}文件存在!"+sftpFilePath);
} catch (SftpException e) {
System.out.println("{}文件不存在!不做处理"+sftpFilePath);
return false;
}
return true;
}
}