接到需求要对第三方公司的服务器进行文件操作,包括文件的上传下载等。。。以下是具体实现代码,希望能帮助到有同样需求的战友,有疑问可以微信交流:【shedexinjing】
package com.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
public class SFTPUtil {
private static final Log log = LogFactory.getLog(SFTPUtil.class);
/**从sftp中后去文件内容
* @param path 远程文件目录
* @param fileName 远程文件
* @return 以 #@# 为分隔的字符串,每一个部分为一行数据
* @throws JSchException
* @throws Exception
*/
public static String downLoadFileTxt(String SFTPType,String path,String fileName) throws JSchException, Exception{
log.info("down_load_file:"+path+"/"+fileName);
Session session = null;
ChannelSftp sftpChannel = null;
InputStream is = null;
BufferedReader buf = null;
StringBuffer content = new StringBuffer();
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
sftpChannel.cd(path);
is = sftpChannel.get(fileName);
if(is==null){
throw new CashException("文件不存在");
}else{
buf = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String tcontent = null;
while((tcontent = buf.readLine())!=null){
if(StringUtils.isNotEmpty(tcontent)){
content.append(CashServiceConstant.DOWN_TEXT_LINE_SPLIT).append(tcontent);
}
}
}
} catch (Exception e) {
throw e;
}finally{
if(is!=null)is.close();
if(buf!=null)buf.close();
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
//去掉最后部分
if(content.toString().startsWith(CashServiceConstant.DOWN_TEXT_LINE_SPLIT)){
return content.toString().replaceFirst(CashServiceConstant.DOWN_TEXT_LINE_SPLIT, "");
}else{
return content.toString();
}
}
/**
* @param SFTPType
* @param sFile 老文件
* @param dFile 先文件
* @return
* @throws JSchException
* @throws Exception
*/
public static boolean rename(String SFTPType,String sFile,String dFile) throws JSchException, Exception{
Session session = null;
ChannelSftp sftpChannel = null;
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
sftpChannel.rename(sFile, dFile);
return true;
} catch (Exception e) {
log.error("",e);
return false;
}finally{
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
}
/**创建文件目录
* @param SFTPType 配置文件中的sftp前缀例如 DJ_SFTP_USER 就等于 SFTPType=DJ
* @param paths 形成靠左/靠前的先创建
* @return
* @throws JSchException
* @throws Exception
*/
public static boolean getMkdirs(String SFTPType,List paths) throws JSchException, Exception{
Session session = null;
ChannelSftp sftpChannel = null;
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
int size = paths.size();
for(int i=0;i getLs(String SFTPType,String path) throws JSchException, Exception{
Session session = null;
ChannelSftp sftpChannel = null;
List fs = new ArrayList();
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
//sftpChannel.cd(path);
log.debug("ls_pwd="+sftpChannel.pwd());
Vector fileList = sftpChannel.ls(path);
fs= parseList(fileList);
} catch (Exception e) {
throw e;
}finally{
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
return fs;
}
/**查看当前目录
* @param SFTPType
* @return
* @throws JSchException
* @throws Exception
*/
public static String getPwd(String SFTPType) throws JSchException, Exception{
Session session = null;
ChannelSftp sftpChannel = null;
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
String pwd = sftpChannel.pwd();
log.debug("pwd="+pwd);
return pwd;
} catch (Exception e) {
throw e;
}finally{
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
}
/**连接ftp
* @param SFTPType 配置文件中的sftp前缀例如 DJ_SFTP_USER 就等于 SFTPType=DJ
* @return
*/
public static Session getSession(String SFTPType){
JSch jsch=new JSch();
Session session = null;
try {
//从properties配置文件中获取服务器参数,自己定义
String user = Properties.getValue(SFTPType+"_SFTP_USER");
String passwd = Properties.getValue(SFTPType+"_SFTP_PASSWD");
String host = Properties.getValue(SFTPType+"_SFTP_HOST");
int port = Properties.getInt(SFTPType+"_SFTP_PORT");
log.debug("user>>"+user);
log.debug("passwd>>"+passwd);
log.debug("host>>"+host);
log.debug("host>>"+host);
session=jsch.getSession(user, host, port);
session.setPassword(passwd);
Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
Integer timeout = CashProperties.getInt(SFTPType+"_SFTP_TIMEOUT");
session.setTimeout(timeout==null?6000:timeout); // 设置timeout时间
session.connect();
return session;
} catch (JSchException e) {
e.printStackTrace();
if(session!=null && session.isConnected()){
session.disconnect();
}
return null;
}
}
/**
* 删除文件夹及其子文件
* @param SFTPType 类型 例如 DJ
* @param directory 上一级文件夹
* @param desdir 目标文件夹
*/
public static void deleteAll(String SFTPType,String directory,String desdir) {
Session session = null;
ChannelSftp sftpChannel = null;
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect();
sftpChannel=(ChannelSftp)channel;
//获取删除目录下的所有文件,要先删除目录下的所有文件再删除文件夹
Vector fileList = null;
try {
fileList = sftpChannel.ls(directory+"/"+desdir);
} catch (Exception e) {
log.debug(directory+"/"+desdir+",该目录不存在");
return;
}
List list= parseList(fileList);
sftpChannel.cd(directory+"/"+desdir);
for (int i = 0; i < list.size(); i++) {
sftpChannel.rm(list.get(i));
}
sftpChannel.cd("../");
sftpChannel.rmdir(desdir);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
}
/**
* 下载文件
* @param SFTPType 类型 例如 DJ
* @param directory ftp上的文件夹
* @param downloadFile 下载的目标文件
* @param saveDirectory 下载保存的路径
* @throws Exception
*/
public static void download(String SFTPType,String directory, String downloadFile, String saveDirectory)
throws Exception
{
Session session = null;
ChannelSftp sftpChannel = null;
FileOutputStream fileOutputStream = null;
try {
String saveFile = saveDirectory + "//" + downloadFile;
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect();
sftpChannel=(ChannelSftp)channel;
sftpChannel.cd(directory);
File file = new File(saveFile);
fileOutputStream = new FileOutputStream(file);
sftpChannel.get(downloadFile, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fileOutputStream!=null){fileOutputStream.close();}
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
}
public static List parseList(Vector fileList){
List list= new ArrayList();
Iterator it = fileList.iterator();
while (it.hasNext())
{
String fileName = ((ChannelSftp.LsEntry)it.next()).getFilename();
if ((".".equals(fileName)) || ("..".equals(fileName))) {
continue;
}
list.add(fileName);
}
return list;
}
/**
* 下载文件,返回InputStream
*/
public static byte[] downLoadFileIo(String SFTPType,String path,String fileName) throws JSchException, Exception{
log.info("下载文件,down_load_file:"+path+"/"+fileName);
Session session = null;
ChannelSftp sftpChannel = null;
InputStream is = null;
byte[] bs = null;
try {
session = getSession(SFTPType);
Channel channel=session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
sftpChannel=(ChannelSftp)channel;
sftpChannel.cd(path);
is = sftpChannel.get(fileName);
bs = readInputStream(is);
} catch (Exception e) {
throw e;
}finally{
if(is!=null)is.close();
if(sftpChannel!=null)sftpChannel.disconnect();
if(session!=null) session.disconnect();
}
return bs;
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}