SFTP多文件上传,删除
公司项目中需要把项目的相关文件上传到服务器的tomcat中,需要在项目中进行以下几步操作:
1.添加项目信息,包括名称,描述,服务器ip,sftp的用户名,密码,端口号等,存在配置,部署,删除等操作
2.配置:显示出文件信息,包括文件路径,目标路径,类型(上传,删除),状态(是否部署),
3.点击部署时进行自动的部署,可以是文件上传,也可以是相关文件的删除
结合网上有关sftp完成的sftp工具类,只使用了多文件上传和文件删除功能,其他没有进行测试,多文件上传需要本地路径和远程路径参数,文件夹删除需要远程路径参数
package MyUtils; import com.jcraft.jsch.*;
import org.apache.log4j.Logger; import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector; /**
* sftp工具类
* */
public class SFTPUtils {
private static Logger log = Logger.getLogger(SFTPUtils.class.getName());
private static ChannelSftp sftp = null;
private static Session sshSession = null;
private static Integer i = 0; /**
* 通过SFTP连接服务器
*/
public static void connect(String ip, String username, String password, Integer port) throws Exception { JSch jsch = new JSch();
try {
if (port <= 0) {
// 连接服务器,采用默认端口
sshSession = jsch.getSession(username, ip);
} else {
// 采用指定的端口连接服务器
sshSession = jsch.getSession(username, ip, port);
} // 如果服务器连接不上,则抛出异常
if (sshSession == null) {
throw new Exception("服务器异常");
} // 设置登陆主机的密码
sshSession.setPassword(password);// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
sshSession.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间
sshSession.connect(300000);
Channel channel = sshSession.openChannel("sftp");
channel.connect(); sftp = (ChannelSftp) channel; } catch (Exception e) {
e.printStackTrace();
throw e;
}
} /**
* 关闭连接
*/
public static void disconnect() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
if (log.isInfoEnabled()) {
log.info("已关闭sftp");
}
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
if (log.isInfoEnabled()) {
log.info("已关闭sshSession");
}
}
}
} /**
* 批量下载文件
*
* @param remotePath:远程下载目录(以路径符号结束)
*
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
*
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
*
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath,
String fileFormat, String fileEndFormat, boolean del) throws SftpException {
List<String> filenames = new ArrayList<String>(); Vector v = sftp.ls(remotePath);
if (v.size() > 0) {
System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
Iterator it = v.iterator();
while (it.hasNext()) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath);
}
}
}
}
}
}
if (log.isInfoEnabled()) {
log.info("download file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is"
+ v.size());
} return filenames;
} /**
* 下载单个文件
*
* @param remotePath:远程下载目录(以路径符号结束)e
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
// sftp.cd(remotePath);
File file = new File(localPath + localFileName);
// mkdirs(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
if (log.isInfoEnabled()) {
log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
} /**
* 上传单个文件
*
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @return
*/
public static void uploadFile(String remotePath, String localPath) throws Exception {
FileInputStream in = null;
File localFile = new File(localPath);
sftp.cd(remotePath);
in = new FileInputStream(localFile);
sftp.put(in, localFile.getName()); if (in != null) {
in.close();
}
} /**
* 批量上传文件
*
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @return
*/
public static boolean bacthUploadFile(String remotePath, String localPath) throws Exception {
File localFile = new File(localPath);
boolean flag = true;
//进入远程路径
try {
if (!isDirExist(remotePath)) {
sftp.mkdir(remotePath);
sftp.cd(remotePath);
} else {
sftp.cd(remotePath);
}
//本地文件上传
File file = new File(localPath);
//本地文件上传方法
copyFile(file, sftp.pwd()); } catch (Exception e) {
e.printStackTrace();
flag = false;
throw e;
} return flag;
} private static void copyFile(File file, String pwd) throws Exception {
if (file.isDirectory()) {
File[] list = file.listFiles();
String fileName = file.getName();
sftp.cd(pwd);
System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);
sftp.mkdir(fileName);
System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
//远程路径发生改变
pwd = pwd + "/" + file.getName();
sftp.cd(file.getName()); for (int i = 0; i < list.length; i++) {
copyFile(list[i], pwd);
}
} else {
//不是目录,直接进入改变后的远程路径,进行上传
sftp.cd(pwd); System.out.println("正在复制文件:" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
outstream = sftp.put(file.getName());
instream = new FileInputStream(file); byte b[] = new byte[1024];
int n;
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
} outstream.flush();
outstream.close();
instream.close(); } } /**
* 删除本地文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
} if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
if (rs && log.isInfoEnabled()) {
log.info("delete file success from local.");
}
return rs;
} /**
* 创建目录
*
* @param createpath
* @return
*/
public static void createDir(String createpath) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
} }
} catch (SftpException e) {
e.printStackTrace();
}
} /**
* 判断目录是否存在
*
* @param directory
* @return
*/
public static boolean isDirExist(String directory) {
try {
Vector<?> vector = sftp.ls(directory);
if (null == vector) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
} /**
* 删除stfp文件
*
* @param directory:要删除文件所在目录
*/
public static void deleteSFTP(String directory) {
try {
if (isDirExist(directory)) {
Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
if (vector.size() == 1) { // 文件,直接删除
sftp.rm(directory);
} else if (vector.size() == 2) { // 空文件夹,直接删除
sftp.rmdir(directory);
} else {
String fileName = "";
// 删除文件夹下所有文件
for (ChannelSftp.LsEntry en : vector) {
fileName = en.getFilename();
if (".".equals(fileName) || "..".equals(fileName)) {
continue;
} else {
deleteSFTP(directory + "/" + fileName);
}
}
// 删除文件夹
sftp.rmdir(directory);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 如果目录不存在就创建目录
*
* @param path
*/
public void mkdirs(String path) {
File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists()) {
f.mkdirs();
}
} /**
* 测试
*/
public static void main(String[] args) {
// 本地存放地址
String localPath = "F:\\java\\src\\main\\webapp\\resources";
// Sftp下载路径
String sftpPath = "/home/sftp/";
List<String> filePathList = new ArrayList<String>();
try {
connect("111.16.123.12", "ftptest1", "123456", 22);
//deleteSFTP(sftpPath);
// 上传
//bacthUploadFile(sftpPath, localPath);
//deleteSFTP("/home/ftp/ff");
} catch (Exception e) {
e.printStackTrace();
} finally {
sftp.disconnect();
}
}
}
SFTP多文件上传,删除的更多相关文章
- 【转】JSch - Java实现的SFTP(文件上传详解篇)
JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...
- JSch - Java实现的SFTP(文件上传详解篇)
JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...
- JSch - Java实现的SFTP(文件上传详解篇) [转载]
文章来源:http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html JSch是Java Secure Channel的缩写.JSch是 ...
- JSch - Java实现的SFTP(文件上传详解篇)(转)
JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...
- github 创建网络仓库 ,使用git工具将本地文件上传/删除 --- 心得
1.前言 使用 git做项目控制版本工具,当然,使用SVN也可以,但是,git让人感觉更先进一些,与GitHub结合,用起来很方便,服务端由官网控制. 而SVN分客户端和服务端,都是个人控制,因此, ...
- SFTP远程文件上传
远程服务器remote_host=192.168.29.142用户为remote_www,用户当前目录为/home/remote_www 本地服务器local_host=192.168.29.135用 ...
- Java使用 SFTP实现文件上传下载
package com.lijy.util; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import co ...
- 配置openssh实现sftp远程文件上传
客服端:winscp等ftp/sftp客户端 服务器:阿里云默认使用的openssh 需求:可以sftp远程传输文件到服务器固定文件夹下,不可远程ssh登录 步骤: 1. 建立系统用户ftpuser及 ...
- oss文件上传删除(批量删除)处理
博主用的是阿里云的oss 首先先在阿里云下载安装sdk,相关的sdk下载请自行到阿里云下载 文档地址 https://help.aliyun.com/document_detail/85580.h ...
随机推荐
- [转帖]AMOLED的技术和OLED有哪些联系和区别
AMOLED的技术和OLED有哪些联系和区别 https://display.ofweek.com/2018-06/ART-11000-2300-30243226.html 硬件资料 导读: ?虽然L ...
- 局域网 FTP建立,搭建一个简易的局域网服务器
1.创建用户名以及密码: 右键我的电脑 -> 管理->本地用户和组->右键用户->新用户----设置用户名密码: 2.安装IIS 和FTP :控制面板->程序->打 ...
- laravel 项目表单中有csrf_token,但一直报错419错误 解决redis连接错误:MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persi
laravel 项目表单中有csrf_token,但一直报错419错误,因为项目中使用到Redis缓存,在强制关闭Redis后出现的问题,查询laravel.log文件查找相关问题 安装redis后在 ...
- bootstrap模态框关闭后清除模态框的数据
https://segmentfault.com/q/1010000008789123 bootstrap模态框第二次打开时如何清除之前的数据? 我用了bootstrap模态框的remote功能,在弹 ...
- CSS硬件加速的好与坏
本文翻译自Ariya Hidayat的Hardware Accelerated CSS: The Nice vs The Naughty.感谢Kyle He帮助校对. 每个人都痴迷于60桢每秒的顺滑动 ...
- Appscanner实验还原code2
import _pickle as pickle from sklearn import svm, ensemble import random from sklearn.metrics import ...
- Kettle 变量(arg位置参数)
1.表输入中使用?占位作为kettle转换变量 数据预览: 获取变量数据: 使用?传入变量 需要勾选替换sql语句中的变量,并选则从步骤插入数据中所在步骤 数据预览
- 【转】说说MySQL中的Redo log Undo log都在干啥
阅读目录(Content) 1 undo 1.1 undo是啥 1.2 undo参数 1.3 undo空间管理 2 redo 2.1 redo是啥 2.2 redo 参数 2.3 redo 空间管理 ...
- Gevent 性能和 gevent.loop 的运用和带来的思考
知乎自己在底层造了非常多的轮子,而且也在服务器部署方面和数据获取方面广泛使用 gevent 来提高并发获取数据的能力.现在开始我将结合实际使用与测试慢慢完善自己对 gevent 更全面的使用和扫盲. ...
- Spring注解 系列之Spring常用注解总结
参考:Spring系列之Spring常用注解总结 (1) Resource 默认是byName的方式进行bean配置,@AutoWired默认是按照byType的方式进行装配bean的:(2)Comp ...