maven
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.50</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
工具类代码
package com.example.cc.util;
import java.io.*;
import java.util.*;
import javax.transaction.SystemException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
public class SFTPOperateUtil {
private static Logger logger = LoggerFactory.getLogger(SFTPOperateUtil.class);
public static Channel getChannel(Session session) {
Channel channel = null;
try {
channel = session.openChannel("sftp");
channel.connect();
logger.info("get Channel success!");
} catch (JSchException e) {
logger.info("get Channel fail!", e);
}
return channel;
}
public static Session getSession(String host, int port, String username, final String password) throws JSchException {
Session session = null;
JSch jsch = new JSch();
jsch.getSession(username, host, port);
session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
logger.info("Session connected!");
return session;
}
/**
* 创建文件夹
*
* @param sftp
* @param dir
* 文件夹名称
*/
public static void mkdir(ChannelSftp sftp, String dir) {
try {
sftp.mkdir(dir);
logger.info("创建文件夹成功!");
} catch (SftpException e) {
logger.info("创建文件夹失败!");
e.getMessage();
}
}
/**
* @param sftp
* @param dir
* 上传目录
* @param file
* 上传文件
* @return
*/
public static Boolean uploadFile(ChannelSftp sftp, String dir, File file) throws Exception{
Boolean result = false;
FileInputStream fileInputStream=null;
try {
sftp.cd(dir);
// File file = new File("D://34.txt"); //要上传的本地文件
if (file != null) {
fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
result = true;
fileInputStream.close();
logger.info("上传成功!");
} else {
logger.info("文件为空!不能上传!!");
}
} catch (Exception e) {
logger.info("上传失败!", e);
}finally {
if (fileInputStream != null){
fileInputStream.close();
}
}
return result;
}
/**
* 上传单个文件
*
* @param directory 上传到SFTP服务器的路径
* @param uploadFileUrl 文件路径
*/
public static Boolean upload(String directory, String uploadFileUrl,ChannelSftp sftp){
Boolean result = false;
File file = new File(uploadFileUrl);
try{
result =uploadFile(sftp,directory, file);
} catch (Exception e) {
logger.error("上传文件异常!", e);
}
return result;
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
* @param sftp
*/
public static Boolean download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
Boolean result = false;
try {
sftp.cd(directory);
sftp.get(downloadFile, saveFile);
result = true;
} catch (Exception e) {
logger.info("下载失败!", e);
}
return result;
}
/**
* 获取文件夹下的文件
*
* @param directory 路径
* @return
*/
public static Vector<?> listFiles(String directory,ChannelSftp sftp){
try{
if(isDirExist(directory,sftp)){
Vector<?> vector = sftp.ls(directory);
//移除上级目录和根目录:"." ".."
vector.remove(0);
vector.remove(0);
return vector;
}
}catch (SftpException e){
logger.error("获取文件夹信息异常!", e);
}
return null;
}
/**
* 获取文件夹下的文件
*
* @param directory 路径
* @return
*/
public static List<String> listFilesName(String directory,ChannelSftp sftp){
List<String> filesName = new ArrayList<String>();
try{
if(isDirExist(directory,sftp)){
Vector<?> vector = sftp.ls(directory);
//移除上级目录和根目录:"." ".."
vector.remove(0);
vector.remove(0);
Iterator iterator = vector.iterator();
while(iterator.hasNext()){
ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
String fileName = file.getFilename();
if(!isDirExist(fileName,sftp)){
filesName.add(fileName);
}
}
}
}catch (SftpException e){
logger.error("获取文件夹信息异常!", e);
}
return filesName;
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public static String delete(String directory, String deleteFile, ChannelSftp sftp) {
String result = "";
try {
sftp.cd(directory);
sftp.rm(deleteFile);
result = "删除成功!";
} catch (Exception e) {
result = "删除失败!";
logger.info("删除失败!", e);
}
return result;
}
/**
* 创建一个文件目录
* @throws SystemException
*/
public static void createDir(String createpath, ChannelSftp sftp) throws SystemException {
try {
if (isDirExist(createpath,sftp)) {
}else{
String pathArry[] = createpath.split("/");
for (int i=0;i<pathArry.length;i++) {
// for (String path : pathArry) {
if (StringUtils.isBlank(pathArry[i])) {
continue;
}
if(StringUtils.isBlank(pathArry[0])&&i==1) {
pathArry[i] ="/"+pathArry[i];
}
if (isDirExist(pathArry[i],sftp)) {
sftp.cd(pathArry[i]);
} else {
// 建立目录
sftp.mkdir(pathArry[i]);
// 进入并设置为当前目录
sftp.cd(pathArry[i]);
}
}
}
logger.info(sftp.pwd());
//sftp.cd(createpath);
} catch (SftpException e) {
throw new SystemException("创建路径错误:" + createpath);
}
}
/**
* 判断目录是否存在
*/
public static boolean isDirExist(String directory,ChannelSftp sftp) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
private static void closeChannel(Channel channel) {
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
}
private static void closeSession(Session session) {
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
public static void closeAll(ChannelSftp sftp, Channel channel, Session session) {
try {
closeChannel(sftp);
closeChannel(channel);
closeSession(session);
} catch (Exception e) {
logger.info("closeAll", e);
}
}
public static void main(String[] args) throws SftpException, IOException {
try {
String password = "08A189769D1B82AA";
Session session = SFTPOperateUtil.getSession("192.168.43.44", 22, "peter", password);
Channel channel = SFTPOperateUtil.getChannel(session);
ChannelSftp sftp = (ChannelSftp)channel;
SFTPOperateUtil.upload("/0/1/2","C:\\Users\\peter\\Desktop\\ftp数据分析存储\\合肥数据同步14张表\\上云数据(1)\\B_APBILL_HEAD20200429.xlsx",sftp);
SFTPOperateUtil.closeAll(sftp,channel,session);
} catch (JSchException e) {
e.getMessage();
}
}
}
835

被折叠的 条评论
为什么被折叠?



