文件服务器采用FreeSSHd,文件服务器配置就不细说了。
直接上代码,该代码可以直接使用。
import com.jcraft.jsch.*; import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author fc
* @version V1.0
* @Title SFTPConnect
* @Package com.jsch
* @Descript :TODO()
* @date : 2018/8/30 下午3:50
*/
public class SftpConnect {
private String user;
private String password;
private String host;
private int port;
private ChannelSftp channelSftp;
private Session session;
private Logger logger = LoggerFactory.getLogger(SftpConnect.class);
private final String NO_SUCH_FILE = "No such file"; public SftpConnect(String user, String password, String host, int port) {
this.user = user;
this.password = password;
this.host = host;
this.port = port;
} private ChannelSftp connect(){
JSch jSch=new JSch();
try {
session=jSch.getSession(user,host,port);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setPassword(password);
session.setConfig(sshConfig);
session.connect();
channelSftp= (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
} catch (JSchException e) {
return null;
}
return channelSftp;
} /**
* 断开连接
*/
private void disconnect() {
channelSftp.disconnect();
session.disconnect();
} public boolean upLoadFile(String path,String filename, InputStream is){
if(channelSftp == null){
logger.debug("初始化sftp连接:连接地址:{}",host);
connect();
logger.trace("sftp连接初始化完成:{}",host);
}
try {
validatePath(path);
channelSftp.put(is,filename);
disconnect();
} catch (SftpException e) {
logger.error("文件上传失败:\n{}",e);
return false;
}
return true;
} /**
* 验证服务器文件夹路径,如不存在则新建
* @param path
*/
private void validatePath(String path) throws SftpException {
try {
channelSftp.lstat(path);
channelSftp.cd(path);
} catch (SftpException e) {
if(NO_SUCH_FILE.equals(e.getMessage())){
logger.debug("{} 不存在,创建该路径",path);
String[] paths = path.split("/");
for(String p : paths){
try {
channelSftp.cd(p);
} catch (SftpException e1) {
channelSftp.mkdir(p);
channelSftp.cd(p);
}
}
}else {
throw e;
}
}
} /**
* 下载文件
* @param path
* @param filename
* @param: is
* @return
*/
public InputStream downFile(String path,String filename){
if(channelSftp == null){
logger.debug("初始化sftp连接:连接地址:{}",host);
connect();
logger.trace("sftp连接初始化完成:{}",host);
}
try {
channelSftp.cd(path);
InputStream is= channelSftp.get(filename);
disconnect();
return is;
} catch (SftpException e) {
return null;
}
}
}