依赖包:com.jcraft.jsch
import com.common.exception.sftp.SftpConnectException;
import com.common.exception.sftp.SftpDowloadException;
import com.common.exception.sftp.SftpOperateException;
import com.common.exception.sftp.SftpUploadException;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
@Slf4j
public class SftpWorker extends Operate {
private String host;
private int port;
private String userName;
private String password;
public static SftpWorker getInstance(){
return new SftpWorker();
}
public SftpWorker option(String host, int port, String userName, String password){
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
return this;
}
@Override
public void upload(InputStream in, String module, String fileName) throws SftpUploadException, SftpConnectException, SftpOperateException {
cdUpload();
try {
this.sftp.cd(module);
} catch (SftpException e) {
try {
this.sftp.mkdir(module);
this.sftp.cd(module);
} catch (SftpException ex) {
log.error("上传失败!原因:创建文件夹异常",e);
throw new SftpUploadException("上传失败!原因:创建文件夹异常");
}
}
try {
this.sftp.put(in,fileName);
} catch (SftpException e) {
log.error("上传失败!原因:上传异常",e);
throw new SftpUploadException("上传失败!原因:上传异常");
}
super.disConnect();
}
@Override
public File dowload(String module, String fileName,String tmpPath) throws SftpConnectException, SftpOperateException, SftpDowloadException {
cdUpload();
try {
File file = new File(tmpPath + File.separator + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
this.sftp.cd(module);
this.sftp.get(fileName,outputStream);
outputStream.close();
return file;
} catch (Exception e1) {
throw new SftpDowloadException("下载文件异常!");
}
}
public File dowload(String module, String fileName, String id, String tmpPath) throws SftpConnectException, SftpOperateException, SftpDowloadException {
cdUpload();
try {
File file = new File(tmpPath + File.separator + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
this.sftp.cd(module);
this.sftp.get(id, outputStream);
outputStream.close();
return file;
} catch (Exception e1) {
throw new SftpDowloadException("下载文件异常!");
}
}
private void cdUpload() throws SftpConnectException, SftpOperateException {
try {
super.connect(this.host,this.port,this.userName,this.password);
this.sftp.cd("upload");
} catch (JSchException e) {
log.error("操作失败!原因:sftp 连接异常",e);
throw new SftpConnectException("上传失败!原因:sftp 连接异常");
} catch (SftpException e) {
log.error("操作失败!原因:上传操作出现异常",e);
throw new SftpOperateException("上传失败!原因:上传操作出现异常");
}
}
}