Java使用sftp定時下載文件的示例代碼
sftp簡介
sftp是Secure File Transfer Protocol的縮寫,安全文件傳送協(xié)議??梢詾閭鬏斘募峁┮环N安全的網絡的加密方法。sftp 與 ftp 有著幾乎一樣的語法和功能。SFTP 為 SSH的其中一部分,是一種傳輸檔案至 Blogger 伺服器的安全方式。其實在SSH軟件包中,已經包含了一個叫作SFTP(Secure File Transfer Protocol)的安全文件信息傳輸子系統(tǒng),SFTP本身沒有單獨的守護進程,它必須使用sshd守護進程(端口號默認是22)來完成相應的連接和答復操作,所以從某種意義上來說,SFTP并不像一個服務器程序,而更像是一個客戶端程序。SFTP同樣是使用加密傳輸認證信息和傳輸的數據,所以,使用SFTP是非常安全的。但是,由于這種傳輸方式使用了加密/解密技術,所以傳輸效率比普通的FTP要低得多,如果您對網絡安全性要求更高時,可以使用SFTP代替FTP。
添加依賴
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
增加配置
sftp:
ip: 192.168.1.60
port: 22
timeout: 60000
retryTime: 3
admin:
username: admin
password: 2k3xrYjbd930.
代碼示例
每天凌晨1點在多個用戶目錄中下載csv文件至本地tmp目錄
@Service
public class SftpTask extends Thread {
private ChannelSftp sftp;
private Session session;
@Value("${sftp.admin.username}")
private String username;
@Value("${sftp.admin.password}")
private String password;
@Value("${sftp.host}")
private String host;
@Value("${sftp.port}")
private Integer port;
private SftpService sftpService;
public EtlSftpTask (SftpService sftpService) {
this.sftpService = sftpService;
}
/**
* 建立sftp連接
*/
private void connect(){
try {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
}catch (JSchException e) {
e.printStackTrace();
}
}
/**
* 關閉sftp連接
*/
public void close(){
try {
if (sftp != null) {
if (sftp.isConnected()) sftp.disconnect();
}
if(session != null){
if (session.isConnected()) session.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載文件到本地
*
* @param source 源文件
* @param target 目標文件
* @throws SftpException 異常
* @throws FileNotFoundException 異常
*/
private void download(String source, String target) throws SftpException, FileNotFoundException {
sftp.get(source, new FileOutputStream(new File(target)));
}
/**
* 處理用戶數據文件
*
* @param root 數據文件根目錄
* @param lastTime 上次處理文件的最后的時間
* @return 本次處理文件的最后的時間
*/
private Integer handle(String root, Integer lastTime) {
String directory = root + "/event/";
Vector files;
try {
files = sftp.ls(directory + "event_*.csv");
} catch (Exception e) {
e.printStackTrace();
return 0;
}
// 文件名
String fileName;
// 臨時文件
String tmpFile;
// 文件更新時間
Integer mTime;
// 文件最后更新時間
Integer maxTime = lastTime;
// 處理用戶文件
for(Object o: files) {
try {
ChannelSftp.LsEntry f = (ChannelSftp.LsEntry) o;
// 文件更新時間
mTime = f.getAttrs().getMTime();
if (mTime <= lastTime) continue;
// 文件名
fileName = f.getFilename();
// 最后處理事件
maxTime = Math.max(maxTime, mTime);
// 下載文件
tmpFile = "/tmp/" + fileName;
download(directory + fileName, tmpFile);
} catch (Exception e) {
// TODO 錯誤日志
e.printStackTrace();
}
}
// 返回文件最后的處理時間
return maxTime;
}
/**
* 每天凌晨1點開始執(zhí)行
*/
@Scheduled(cron = "0 0 1 * * *")
public void task () {
// 獲取sftp連接
connect();
String root;
Integer lastTime;
Long cid;
Integer maxTime = lastTime;
// 獲取用戶列表
for (SftpDTO sftpDTO: sftpService.findAll()) {
// 用戶主目錄
root = sftpDTO.getSftpRoot();
// 上次處理文件的最后時間
lastTime = sftpDTO.getLastTime();
maxTime = Math.max(maxTime, handle(root, lastTime));
// 更新最后處理時間
if (!maxTime.equals(lastTime)) {
sftpDTO.setLastTime(maxTime);
sftpService.update(sftpDTO);
}
}
// 釋放sftp資源
close();
}
}
總結
以上所述是小編給大家介紹的Java使用sftp定時下載文件的示例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!

