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 ...
随机推荐
- bzoj1682[Usaco2005 Mar]Out of Hay 干草危机*
bzoj1682[Usaco2005 Mar]Out of Hay 干草危机 题意: 给个图,每个节点都和1联通,奶牛要从1到每个节点(可以走回头路),希望经过的最长边最短. 题解: 求最小生成树即可 ...
- 简易防止U盘中毒
1.将U盘插入电脑,打开u盘 2.在U盘里面新建一个文本文档,将文本文档重命名autorun.inf保存完成. 3.为了防止误删次文件可以将属性设为影藏,就完成了.
- PHP实现多继承
题问php是否支持多继承? 答案:不可以,只支持单继承. 如何实现多继承呢? 答案:可以使用 interface 或 trait 实现 . interface这里我们就不做过多的说明了,它的原理就是一 ...
- 【JUnit测试】总结
什么是Junit? Junit是xUnit的一个子集,在c++,paython,java语言中测试框架的名字都不相同 xUnit是一套基于测试驱动开发的测试框架 其中的断言机制:将程序预期的结果与程序 ...
- SpringSecurity+Oauth2+Jwt实现toekn认证和刷新token
简单描述:最近在处理鉴权这一块的东西,需求就是用户登录需要获取token,然后携带token访问接口,token认证成功接口才能返回正确的数据,如果访问接口时候token过期,就采用刷新token刷新 ...
- 前端学习(四):body标签(二)
进击のpython ***** 前端学习--body标签 接着上一节,我们看一下还有没有什么网址 果不其然,在看到新闻类的网址的时候 我们发现还有许多的不一样的东西! 使用ul,添加新闻信息列表 这个 ...
- C#中Session的用法详细介绍
Session模型简介 在学习之前我们会疑惑,Session是什么呢?简单来说就是服务器给客户端的一个编号.当一台WWW服务器运行时,可能有若干个用户浏览正在运正在这台服务器上的网站.当每 个用户首次 ...
- pycharm 退出虚拟环境
pycharm 内置虚拟环境 venv 如果要退出就直接 deactivate 命令就行 运行的话直接在命令行输python3 文件名
- c# Dictionary的使用
创建: Dictionary<string, OverCaseData> dataDic = new Dictionary<string, OverCaseData>() ...
- bzoj 2839 集合计数 容斥\广义容斥
LINK:集合计数 容斥简单题 却引出我对广义容斥的深思. 一直以来我都不理解广义容斥是为什么 在什么情况下使用. 给一张图: 这张图想要表达的意思就是这道题目的意思 而求的东西也和题目一致. 特点: ...