Java實現Sftp下載檔案功能
阿新 • • 發佈:2020-06-24
由於在業務中會經常有上傳和下載的功能需要實現,所以掌握基本fileUpload技能是必不可少的。當然,從Sftp伺服器下載檔案並解析是和我們平時使用的從普通檔案伺服器下載檔案是不同的,接下來,我就來一步一步做個記錄。
1.引入依賴包
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
複製程式碼
2.實現工具類
jsch常用密碼登陸和金鑰認證的形式進行sftp伺服器登陸 。
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Properties;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@Slf4j
//此處註解用來將本類交給Spring管理,也就是讓Springboot啟動類可以掃描到
@Component
public class SFtpUtil {
public static final String NO_FILE = "No such file";
private ChannelSftp sftp = null;
private Session sshSession = null;
private String username;
private String password;
private String host;
private int port;
//輸入自己的密碼賬號ip地址即可
public SFtpUtil() {
this.username = "*******";
this.password = "*******";
this.host = "*******";
this.port = 22;
}
/**
* 連線sftp伺服器
*
* @return ChannelSftp sftp型別
*/
public ChannelSftp connect() {
log.info("ftp連線開始host=" + host + "port" + port + "username=" + username);
JSch jsch = new JSch();
try {
jsch.getSession(username,host,port);
sshSession = jsch.getSession(username,port);
log.info("ftp---Session created.");
sshSession.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking","no");
sshSession.setConfig(properties);
sshSession.connect();
log.info("ftp---Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
log.info("Opening Channel.");
sftp = (ChannelSftp) channel;
log.info("ftp---Connected to " + host);
} catch (JSchException e) {
throw new BadRequestException(null,SFtpUtil.class.getSimpleName(),"connect異常" + e.getMessage());
}
return sftp;
}
複製程式碼
3.單個下載方法
/**
* 下載單個檔案
* @param directory 遠端下載目錄(以路徑符號結束)
* @param remoteFileName FTP伺服器檔名稱 如:xxx.txt ||xxx.txt.zip
* @param localFile 本地檔案路徑 如 D:\\xxx.txt
* @return
* @throws BadRequestException //自定義異常
*/
public File downloadFile(String directory,String remoteFileName,String localFile){
log.info("ftp下載檔案" + remoteFileName + "開始");
connect();
File file = null;
OutputStream output = null;
try {
file = new File(localFile);
if (file.exists()) {
file.delete();
}
boolean newFile = file.createNewFile();
//進入FTP伺服器檔案目錄
sftp.cd(directory);
output = new FileOutputStream(file);
sftp.get(remoteFileName,output);
log.info("DownloadFile:" + remoteFileName + "success from sftp");
} catch (SftpException e) {
if (e.toString().equals(NO_FILE)) {
log.info("sftp下載檔案失敗" + directory + remoteFileName + "不存在");
throw new BadRequestException(null,"ftp下載檔案失敗" + directory + remoteFileName + "不存在");
}
throw new BadRequestException(null,"ftp目錄或者檔案異常,檢查ftp目錄和檔案" + e.toString());
} catch (FileNotFoundException e) {
throw new BadRequestException(null,"本地目錄異常,請檢查" + file.getPath() + e.getMessage());
} catch (IOException e) {
throw new BadRequestException(null,"建立本地檔案失敗" + file.getPath() + e.getMessage());
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
throw new BadRequestException(null,"Close stream error" + e.getMessage());
}
}
disconnect();
}
log.info("ftp下載檔案結束");
return file;
}
複製程式碼
4.關閉連線
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
this.sftp = null;
log.info("sftp is closed already");
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
this.sshSession = null;
log.info("sshSession is closed already");
}
}
}
複製程式碼