1.SFtp 与Ftp 的区别:
简单来说,SFtp安全性高
2.SFtp工具类
import com.jcraft.jsch.*;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class SFtpUtils {
Logger log = LoggerFactory.getLogger(SFtpUtils.class);
private Session session = null;
private ChannelSftp channel = null;
//服务器ip地址
public String host;
//端口号
public int port;
//连接超时时间(单位:秒)
private int timeout;
//用户名
public String username;
//密码
public String password;
/**
* SFTP 安全文件传送协议
*
* @param host SFTP服务器IP地址
* @param port SFTP服务器端口
* @param timeout 连接超时时间,单位毫秒
* @param username 用户名
* @param password 密码
*/
public SFtpUtils(String host, int port, int timeout, String username, String password) {
this.host = host;
this.port = port;
this.timeout = timeout;
this.username = username;
this.password = password;
}
/**
* 登录sftp
*
* @return
*/
public boolean login() {
try {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(timeout);
session.connect();
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
return true;
} catch (Exception e) {
log.error("sftp 服务器登录失败! " + e);
return false;
}
}
/**
* 登出
*/
public void logout() {
if (channel != null) {
channel.quit();
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
/**
* 上传文件
*
* @param pathName 服务器目录
* @param fileName 服务器上保存的文件名
* @param is 输入文件流
* @return
*/
public boolean uploadFile(String pathName, String fileName, InputStream is) {
if (!changeDir(pathName)) {
return false;
}
try {
channel.put(is, fileName, ChannelSftp.OVERWRITE);
if (!existFile(fileName)) {
return false;
}
return true;
} catch (SftpException e) {
log.error("上传文件失败!", e);
return false;
} finally {
//changeDir(currentDir());
}
}
/**
* 上传文件
*
* @param pathName 服务器目录
* @param fileName 服务器上保存的文件名
* @param localFile 本地文件
* @return
*/
public boolean uploadFile(String pathName, String fileName, String localFile) {
if (!changeDir(pathName)) {