java SFTP工具类
需要导入jsch-0.1.52.jar
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; /**
* 提供SFTP处理文件服务
*
* @author krm-hehongtao
* @date 2016-02-29
*
*/
public class SFTPUtil {
private JSch jSch = null;
private ChannelSftp sftp = null;// sftp主服务
private Channel channel = null;
private Session session = null; private String hostName = "192.168.0.177";// 远程服务器地址
private int port = 22;// 端口
private String userName = "weblogic";// 用户名
private String password = "weblogic";// 密码 public SFTPUtil(String hostName, int port, String userName, String password) {
this.hostName = hostName;
this.port = port;
this.userName = userName;
this.password = password;
} /**
* 连接登陆远程服务器
*
* @return
*/
public boolean connect() throws Exception {
try {
jSch = new JSch();
session = jSch.getSession(userName, hostName, port);
session.setPassword(password); session.setConfig(this.getSshConfig());
session.connect(); channel = session.openChannel("sftp");
channel.connect(); sftp = (ChannelSftp) channel;
System.out.println("登陆成功:" + sftp.getServerVersion()); } catch (JSchException e) {
System.err.println("SSH方式连接FTP服务器时有JSchException异常!");
System.err.println(e.getMessage());
throw e;
}
return true;
} /**
* 关闭连接
*
* @throws Exception
*/
private void disconnect() throws Exception {
try {
if (sftp.isConnected()) {
sftp.disconnect();
}
if (channel.isConnected()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
} catch (Exception e) {
throw e;
}
} /**
* 获取服务配置
*
* @return
*/
private Properties getSshConfig() throws Exception {
Properties sshConfig = null;
try {
sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no"); } catch (Exception e) {
throw e;
}
return sshConfig;
} /**
* 下载远程sftp服务器文件
*
* @param remotePath
* @param remoteFilename
* @param localFilename
* @return
*/
public boolean downloadFile(String remotePath, String remoteFilename, String localFilename)
throws SftpException, IOException, Exception {
FileOutputStream output = null;
boolean success = false;
try {
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} File localFile = new File(localFilename);
// 有文件和下载文件重名
if (localFile.exists()) {
System.err.println("文件: " + localFilename + " 已经存在!");
return success;
}
output = new FileOutputStream(localFile);
sftp.get(remoteFilename, output);
success = true;
System.out.println("成功接收文件,本地路径:" + localFilename);
} catch (SftpException e) {
System.err.println("接收文件时有SftpException异常!");
System.err.println(e.getMessage());
return success;
} catch (IOException e) {
System.err.println("接收文件时有I/O异常!");
System.err.println(e.getMessage());
return success;
} finally {
try {
if (null != output) {
output.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
} /**
* 上传文件至远程sftp服务器
*
* @param remotePath
* @param remoteFilename
* @param localFileName
* @return
*/
public boolean uploadFile(String remotePath, String remoteFilename, String localFileName)
throws SftpException, Exception {
boolean success = false;
FileInputStream fis = null;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
}
File localFile = new File(localFileName);
fis = new FileInputStream(localFile);
// 发送文件
sftp.put(fis, remoteFilename);
success = true;
System.out.println("成功发送文件,本地路径:" + localFileName);
} catch (SftpException e) {
System.err.println("发送文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
throw e;
} catch (Exception e) {
System.err.println("发送文件时有异常!");
System.err.println(e.getMessage());
throw e;
} finally {
try {
if (null != fis) {
fis.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
} /**
* 上传文件至远程sftp服务器
*
* @param remotePath
* @param remoteFilename
* @param input
* @return
*/
public boolean uploadFile(String remotePath, String remoteFilename, InputStream input)
throws SftpException, Exception {
boolean success = false;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} // 发送文件
sftp.put(input, remoteFilename);
success = true;
} catch (SftpException e) {
System.err.println("发送文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
throw e;
} catch (Exception e) {
System.err.println("发送文件时有异常!");
System.err.println(e.getMessage());
throw e;
} finally {
try {
if (null != input) {
input.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
} }
return success;
} /**
* 删除远程文件
*
* @param remotePath
* @param remoteFilename
* @return
* @throws Exception
*/
public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
boolean success = false;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} // 删除文件
sftp.rm(remoteFilename);
System.err.println("删除远程文件" + remoteFilename + "成功!");
success = true;
} catch (SftpException e) {
System.err.println("删除文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
return success;
} catch (Exception e) {
System.err.println("删除文件时有异常!");
System.err.println(e.getMessage());
return success;
} finally {
// 关闭连接
disconnect();
}
return success;
} /**
* 遍历远程文件
*
* @param remotePath
* @return
* @throws Exception
*/
public List<String> listFiles(String remotePath) throws SftpException {
List<String> ftpFileNameList = new ArrayList<String>();
Vector<LsEntry> sftpFile = sftp.ls(remotePath);
LsEntry isEntity = null;
String fileName = null;
Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
while (sftpFileNames.hasNext()) {
isEntity = (LsEntry) sftpFileNames.next();
fileName = isEntity.getFilename();
System.out.println(fileName);
ftpFileNameList.add(fileName);
}
return ftpFileNameList;
} /**
* 判断路径是否存在
*
* @param remotePath
* @return
* @throws SftpException
*/
public boolean isExist(String remotePath) throws SftpException {
boolean flag = false;
try {
sftp.cd(remotePath);
System.out.println("存在路径:" + remotePath);
flag = true;
} catch (SftpException sException) { } catch (Exception Exception) {
}
return flag;
} public String getHostName() {
return hostName;
} public void setHostName(String hostName) {
this.hostName = hostName;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} /**
* 测试方法
*
*/
public static void main(String[] args) {
try {
SFTPUtil sftp = new SFTPUtil("192.168.0.177", 22, "weblogic", "weblogic");
System.out.println(new StringBuffer().append(" 服务器地址: ")
.append(sftp.getHostName()).append(" 端口:").append(sftp.getPort())
.append("用户名:").append(sftp.getUserName()).append("密码:")
.append(sftp.getPassword().toString()));
sftp.connect();
if (sftp.isExist("/home/weblogic/project")) {
sftp.listFiles("/home/weblogic/project");
sftp.downloadFile("/home/weblogic/project", "S123456_20150126.csv",
"D:\\S123456_20150126.csv");
// sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt");
// sftp.deleteFile("\\", "test.txt");
}
} catch (Exception e) {
System.out.println("异常信息:" + e.getMessage());
}
}
}
java SFTP工具类的更多相关文章
- 基于JSch的Sftp工具类
本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...
- SFTP工具类 操作服务器
package com.leadbank.oprPlatform.util;import com.jcraft.jsch.*;import com.jcraft.jsch.ChannelSftp.Ls ...
- SFTP工具类
1.SFTP搭建方法: 地址: http://www.jb51.net/article/101405.htm https://blog.csdn.net/helloloser/article/deta ...
- Java Properties工具类详解
1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- MinerUtil.java 爬虫工具类
MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
随机推荐
- [Qt2D绘图]-04绘制文字&&绘制路径
注:学习自<Qt Creator 快速入门>第三版. 文档中的示例参考 Qt Example推荐:Painter Paths Example和Vector Deformation ...
- Ethical Hacking - Web Penetration Testing(7)
VULNS MITIGATION 1. File Upload Vulns - Only allow safe files to be updated. 2. Code Execution Vulns ...
- INS-40718 和 INS - 30516
RAC 安装的时候报错, INS-40718 这个是自己填写的 scan name 和 /etc/hosts 里定义的不一致 可以cat /etc/hosts 看一下 INS - 30 ...
- C# 泛型中的数据类型判定与转换
提到类型转换,首先要明确C#中的数据类型,主要分为值类型和引用类型: 1.常用的值类型有:(struct) 整型家族:int,byte,char,short,long等等一系列 浮点家族:float, ...
- 【思维+大数(高精度)】number 计蒜客 - 45276
题目: 求 1 到 10^n 的数字中有 3 的数字的数量. 输入格式 1 个整数 n. 输出格式 共一行,1 个整数,表示答案. 数据范围 对于 10% 的数据,n≤8 对于 30% 的数据,n≤1 ...
- 题解 洛谷 P4695 【[PA2017]Banany】
考虑用动态点分治来解决像本题这样带修的树上路径问题. 首先对原树进行点分治,建出点分树,在点分树每个节点上用动态开点线段树来维护以该节点为起点,到其点分树子树中每个节点的利润. 查询时只需在点分树上当 ...
- jq转盘抽奖
之前项目的时候要写一个抽奖,自己写了以后就记录一下. 先是html <div class="turntable_zhan"> <img class="y ...
- Lua中 pairs和ipairs的区别
Lua系列–pairs和ipairsLua中Table的存储方式在看二者的区别之前,我们首先来看一下Lua中的table是如何在内存中进行分配的.Table的组成:1.哈希表 用来存储Key-Valu ...
- webpack 4.x版本手动配置
运行 npm init -y 快速初始化项目 在项目根目录创建src源代码目录和dist产品目录 在src目录下创建 index.html mani.js文件如果后期使用entry打包,这里可以手动创 ...
- AI大厂算法测试心得:人脸识别关键指标有哪些?
仅仅在几年前,程序员要开发一款人脸识别应用,就必须精通算法的编写.但现在,随着成熟算法的对外开放,越来越多开发者只需专注于开发垂直行业的产品即可. 由调查机构发布的<中国AI产业地图研究> ...