1、Maven引入jar

 <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

2、Test类

package com.tandaima.pub;

import java.io.*;
import java.util.Properties; import com.jcraft.jsch.*; /**
* User longpizi
* Date: 2019/10/30
* Time: 14:40
*/
public class SftpUtil {
public static final String CHANNELTYPE_SFTP="sftp";
public static final String CHANNELTYPE_EXEC="exec";
private Session session;//会话
private Channel channel;//连接通道
private ChannelSftp sftp;// sftp操作类
private JSch jsch;
protected static String host=getLinuxParam()[0];
protected static String port=getLinuxParam()[1];
protected static String user=getLinuxParam()[2];
protected static String password=getLinuxParam()[3]; private static String[] getLinuxParam(){
Properties props=new Properties();//读取文件类型创建对象。
try {
ClassLoader classLoader = SftpUtil.class.getClassLoader();// 读取属性文件
InputStream in = classLoader.getResourceAsStream("linux.properties");
props.load(in); /// 加载属性列表
if(in!=null){
in.close();
}
} catch (Exception e) {
System.out.println("Linux连接参数异常:"+e.getMessage());
}
String[] str={"","","",""};
str[0]=props.getProperty("file.host");
str[1]=props.getProperty("file.port");
str[2]=props.getProperty("file.user");
str[3]=props.getProperty("file.password");
return str;
}
/**
* 断开连接
*/
public static void closeConnect(Session session, Channel channel, ChannelSftp sftp){
if (null != sftp) {
sftp.disconnect();
sftp.exit();
sftp = null;
}
if (null != channel) {
channel.disconnect();
channel = null;
}
if (null != session) {
session.disconnect();
session = null;
}
System.out.println("连接已关闭");
} /**
* 连接ftp/sftp服务器
*
* @param sftpUtil 类
*/
public static void getConnect(SftpUtil sftpUtil,String openChannelType) throws Exception {
Session session = null;
Channel channel = null; JSch jsch = new JSch();
session = jsch.getSession(user, host, Integer.parseInt(port));
session.setPassword(password);
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
// 不验证 HostKey
session.setConfig("StrictHostKeyChecking", "no");
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
System.out.println("连接服务器失败");
}
channel = session.openChannel(openChannelType);
try {
channel.connect();
} catch (Exception e) {
if (channel.isConnected())
channel.disconnect();
System.out.println("连接服务器失败");
}
sftpUtil.setJsch(jsch);
if(openChannelType.equals(CHANNELTYPE_SFTP)){
sftpUtil.setSftp((ChannelSftp) channel);
}
sftpUtil.setChannel(channel);
sftpUtil.setSession(session); } /**
* 上传文件
*
* @param directory 上传的目录-相对于SFPT设置的用户访问目录
* @param uploadFile 要上传的文件全路径
*/
public static boolean upload(String directory, String uploadFile) {
boolean resultState=false;
SftpUtil sftpUtil = new SftpUtil();
try{
getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
Session session = sftpUtil.getSession();
Channel channel = sftpUtil.getChannel();
ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
try {
sftp.cd(directory); //进入目录
} catch (SftpException sException) {
if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) { //指定上传路径不存在
sftp.mkdir(directory);//创建目录
sftp.cd(directory); //进入目录
}
}
File file = new File(uploadFile);
InputStream in = new FileInputStream(file);
sftp.put(in, file.getName());
in.close();
closeConnect(session, channel, sftp);
resultState=true;
}catch (Exception e){
System.out.println("上传文件异常");
}
return resultState;
} /**
* 获取已连接的Sftp
* @return SftpUtil
*/
public static SftpUtil getConnectSftp(){
SftpUtil sftpUtil=new SftpUtil();
try {
getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
return sftpUtil;
}catch (Exception e){
System.out.println("下载文件异常");
}
return null;
} /**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
*/
public static boolean delete(String directory, String deleteFile){
boolean resultState=false;
SftpUtil sftpUtil=new SftpUtil();
try {
getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
Session session = sftpUtil.getSession();
Channel channel = sftpUtil.getChannel();
ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
sftp.cd(directory); //进入的目录应该是要删除的目录的上一级
sftp.rm(deleteFile);//删除目录
closeConnect(session,channel,sftp);
resultState=true;
}catch (Exception e){
System.out.println("删除文件异常");
}
return resultState;
} /**
JSch有三种文件传输模式:
(1)OVERWRITE:完全覆盖模式。JSch的默认文件传输模式,传输的文件将覆盖目标文件。
(2)APPEND:追加模式。如果目标文件已存在,则在目标文件后追加。
(3)RESUME:恢复模式。如果文件正在传输时,由于网络等原因导致传输中断,则下一次传输相同的文件
时,会从上一次中断的地方续传。
*/
/**
* 追加文件内容
* @param remoteFile 原文件路径
* @param in 追加内容
* @return true成功,false失败
*/
public static boolean appendFileContent(String remoteFile, InputStream in){
boolean resultState=false;
SftpUtil sftpUtil = new SftpUtil();
try{
getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
Session session = sftpUtil.getSession();
Channel channel = sftpUtil.getChannel();
ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
OutputStream out = sftp.put(remoteFile, ChannelSftp.APPEND);
int bufferSize=1024;
byte[] buff = new byte[bufferSize]; // 设定每次传输的数据块大小
int read;
if (out != null) {
do {
read = in.read(buff, 0, buff.length);
if (read > 0) {
out.write(buff, 0, read);
}
out.flush();
} while (read >= 0);
}
if(out!=null){
out.close();
}
closeConnect(session, channel, sftp);
resultState=true;
}catch (Exception e){
System.out.println("写入文件异常");
}
return resultState;
} /**
* 创建文件
* @param fileDir 文件路径
* @param fileName 文件名称
* @return
*/
public static boolean createFile(String fileDir,String fileName){
try{
execute("mkdir -p "+fileDir+"\n" +
"touch "+fileDir+"/"+fileName);
}catch (Exception e){
return false;
}
return true;
} /**
* 创建文件夹
* @param fileDir 文件路径
* @return true成功/false失败
*/
public static boolean createFileDir(String fileDir){
try{
execute("mkdir -p "+fileDir+"");
}catch (Exception e){
return false;
}
return true;
} /**
* 压缩文件夹为ZIP
* @param fileDir 文件路径
* @param fileName 文件名称
* @param additionalName 压缩附加名
* @return
*/
public static boolean zipDir(String fileDir,String fileName,String additionalName){
try{
execute("cd "+fileDir+"\n" +
"zip -r "+fileDir+"/"+fileName+additionalName+".zip "+fileName);
}catch (Exception e){
return false;
}
return true;
} /**
* 获取文件大小 单位(K)
* @param fileDir 文件路径
* @return 文件大小
*/
public static long getFileSize(String fileDir){
return Long.parseLong(execute("ls -l "+fileDir+" | awk '{ print $5 }'"));
}
/**
* 执行liunx 命令
* @param command 命令内容
* @return 命令输出
*/
private static String execute(String command){
SftpUtil sftpUtil=new SftpUtil();
StringBuffer strBuffer=new StringBuffer();
try {
getConnect(sftpUtil,CHANNELTYPE_EXEC);
// Create and connect session.
Session session = sftpUtil.getSession(); // Create and connect channel.
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command); channel.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader(channel
.getInputStream())); channel.connect();
System.out.println("命令: " + command);
// 获取命令的输出
String line;
while ((line = input.readLine()) != null) {
strBuffer.append(line);
}
input.close();
closeConnect(session,channel,null);
} catch (Exception e) {
e.printStackTrace();
}
return strBuffer.toString();
}
// public static void main(String[] args) throws FileNotFoundException {
// String window_dir="C:\\Users\XXX\\Desktop\\test\\test.txt";
// String liunx_dir="/usr/local/longpizi";
// try {
//// System.out.println(upload(liunx_dir,window_dir));
//// System.out.println(download(liunx_dir,"test.txt","C:\\Users\\XXX\\Desktop\\test"));
//// System.out.println(delete(liunx_dir,"test.txt"));
//
//// InputStream inputStream = new ByteArrayInputStream("this is test".getBytes());
//// System.out.println(appendFileContent(liunx_dir+"/test.txt",inputStream));
//
//// String command="touch /usr/local/longlin/longpizi.sh\nmkdir -p sss";
//// System.out.println(execute(command));
//
//// System.out.println(createFile("/usr/local/longlin/test/sfdsfdf","sss.txt"));
// } catch (Exception e) {
// e.printStackTrace();
// }
// } public JSch getJsch() {
return jsch;
} public void setJsch(JSch jsch) {
this.jsch = jsch;
} public Session getSession() {
return session;
} public void setSession(Session session) {
this.session = session;
} public Channel getChannel() {
return channel;
} public void setChannel(Channel channel) {
this.channel = channel;
} public ChannelSftp getSftp() {
return sftp;
} public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
}

最新文章

  1. Android开发学习路线图
  2. Java学习——HashMap
  3. 2016年湖南省第十二届大学生计算机程序设计竞赛Problem A 2016 找规律归类
  4. html里的添加视频特效(美化,丰富内容)
  5. js实现一套代码来控制所有的运动,图片的淡入淡出,winth,height的变宽
  6. 02-JAVA中的基本语法
  7. DDD:Can I DDD?
  8. Android手机_软件安装目录
  9. homework-06&amp;homework-09
  10. unity3d遍历出Cube里面所有子对象
  11. 如何判断是REQUEST请求是来自移动终端还是来自PC端
  12. oracle常用查询三
  13. android launcher开发之图标背景以及默认配置
  14. React 进修之路(2)
  15. 【1414软工助教】团队作业10——复审与事后分析(Beta版本) 得分榜
  16. cuda小白基础教程
  17. deeplearing4j学习以及踩过的坑
  18. SC命令
  19. 吴恩达机器学习笔记51-初始值重建的压缩表示与选择主成分的数量K(Reconstruction from Compressed Representation &amp; Choosing The Number K Of Principal Components)
  20. 排序算法系列:选择排序算法JAVA版(靠谱、清晰、真实、可用、不罗嗦版)

热门文章

  1. 159-PHP strstr函数,取最后几个字符和除去最后几个字符
  2. HDU 4866 多校1 主席树+扫描线
  3. ACM-奇特的立方体
  4. [ACTF2020 新生赛]Exec
  5. java的JDBC的事务学习
  6. Dubbo与SpringCloud
  7. 【Java Spring 进阶之路 】1.Spring 是什么?
  8. Arduino -- variables
  9. 第二阶段scrum-2
  10. mysql第四篇:数据操作之多表查询