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 ...
随机推荐
- vue + echart 实现中国地图 和 省市地图(可切换省份)
一.中国地图 1.先导入echarts,然后再main.js里引入echarts // 引入echartsimport echarts from 'echarts'Vue.prototype.$ech ...
- Oracle-常见的命令
--------------输入一下指令,按下快捷键 F8 select * from emp; --------------创建表格 create table 表名( 字段名1 数据类型1, 字段名 ...
- apache 添加多个站点
虚拟主机 (Virtual Host) 是在同一台机器搭建属于不同域名或者基于不同 IP 的多个网站服务的技术.可以为运行在同一物理机器上的各个网站指配不同的 IP 和端口,也可让多个网站拥有不同的域 ...
- python爬虫入门(3)----- scrapy
scrapy 简介 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 其最初是为了 页面抓取 (更确切来说, 网络 ...
- js原型、原型链
之前有说过继承,在js中没有类,所以在new的后面,放的是构造函数,在构造函数中有一个属性prototype,js的继承全靠它. 在js中对象的类型有很多,常见的就是普通对象,和函数对象,在对象中都会 ...
- Java程序斗地主发牌代码,List、Map集合的应用
Java集合存储的灵活运用List集合存储 54个编号 Map <key,value> key 对应的是编号 , value 是 牌的花色(红方梅黑)+ 具体的一张牌 ,比如 黑桃2 用2 ...
- 如何在CSDN博客开头处加上版权声明?
1.首先在CSDN账号头像处打开"管理博客"选项. 2.然后在管理博客界面左侧找到设置下面的"博客设置"选项. 3.将博客设置里的"版权声明" ...
- .NET Core学习笔记(7)——Exception最佳实践
1.为什么不要给每个方法都写try catch 为每个方法都编写try catch是错误的做法,理由如下: a.重复嵌套的try catch是无用的,多余的. 这一点非常容易理解,下面的示例代码中,O ...
- 如何使用Istio 1.6管理多集群中的微服务?
假如你正在一家典型的企业里工作,需要与多个团队一起工作,并为客户提供一个独立的软件,组成一个应用程序.你的团队遵循微服务架构,并拥有由多个Kubernetes集群组成的广泛基础设施. 由于微服务分布在 ...
- JavaScript Symbol对象
JavaScript Symbol对象 Symbol Symbol对象是es6中新引进的一种数据类型,它的作用非常简单,就是用于防止属性名冲突而产生. Symbol的最大特点就是值是具有唯一性,这代表 ...