Java中通過sftp協(xié)議實(shí)現(xiàn)上傳下載的示例代碼
在java開發(fā)中,遇到需要將linux系統(tǒng)中指定目錄下的文件下載到windows本地的需求,下面聊聊通過sftp協(xié)議實(shí)現(xiàn)上傳和下載。
1、SFTP協(xié)議
JSch是Java Secure Channel的縮寫。JSch是一個(gè)SSH2的純Java實(shí)現(xiàn)。它允許你連接到一個(gè)SSH服務(wù)器,并且可以使用端口轉(zhuǎn)發(fā),X11轉(zhuǎn)發(fā),文件傳輸?shù)?,?dāng)然你也可以集成它的功能到你自己的應(yīng)用程序。
SFTP是Secure File Transfer Protocol的縮寫,安全文件傳送協(xié)議。可以為傳輸文件提供一種安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務(wù)器的安全方式。SFTP是使用加密傳輸認(rèn)證信息和傳輸?shù)臄?shù)據(jù),所以,使用SFTP是非常安全的。但是,由于這種傳輸方式使用了加密/解密技術(shù),所以傳輸效率比普通的FTP要低得多,如果您對(duì)網(wǎng)絡(luò)安全性要求更高時(shí),可以使用SFTP代替FTP。
2、SFTP核心類
ChannelSftp類是JSch實(shí)現(xiàn)SFTP核心類,它包含了所有SFTP的方法,如:
- put(): 文件上傳
- get(): 文件下載
- cd(): 進(jìn)入指定目錄
- ls(): 得到指定目錄下的文件列表
- rename(): 重命名指定文件或目錄
- rm(): 刪除指定文件
- mkdir(): 創(chuàng)建目錄
- rmdir(): 刪除目錄
其他參加源碼。
JSch支持三種文件傳輸模式: - OVERWRITE 完全覆蓋模式,這是JSch的默認(rèn)文件傳輸模式,即如果目標(biāo)文件已經(jīng)存在,傳輸?shù)奈募⑼耆采w目標(biāo)文件,產(chǎn)生新的文件。
- RESUME 恢復(fù)模式,如果文件已經(jīng)傳輸一部分,這時(shí)由于網(wǎng)絡(luò)或其他任何原因?qū)е挛募鬏斨袛?,如果下一次傳輸相同的文件,則會(huì)從上一次中斷的地方續(xù)傳。
- APPEND 追加模式,如果目標(biāo)文件已存在,傳輸?shù)奈募⒃谀繕?biāo)文件后追加。
編寫一個(gè)工具類,根據(jù)ip,用戶名及密碼得到一個(gè)SFTP channel對(duì)象,即ChannelSftp的實(shí)例對(duì)象,在應(yīng)用程序中就可以使用該對(duì)象來調(diào)用SFTP的各種操作方法:
public class SFTPChannel {
Session session = null;
Channel channel = null;
private static final Logger LOG = Logger.getLogger(SFTPChannel.class.getName());
public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {
String ftpHost = sftpDetails.get(“host”);
String port = sftpDetails.get("port");
String ftpUserName = sftpDetails.get("username");
String ftpPassword = sftpDetails.get("password");
int ftpPort = 22;
if (port != null && !port.equals("")) {
ftpPort = Integer.valueOf(port);
}
JSch jsch = new JSch(); // 創(chuàng)建JSch對(duì)象
session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據(jù)用戶名,主機(jī)ip,端口獲取一個(gè)Session對(duì)象
LOG.debug("Session created.");
if (ftpPassword != null) {
session.setPassword(ftpPassword); // 設(shè)置密碼
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 為Session對(duì)象設(shè)置properties
session.setTimeout(timeout); // 設(shè)置timeout時(shí)間
session.connect(); // 通過Session建立鏈接
LOG.debug("Session connected.");
LOG.debug("Opening Channel.");
channel = session.openChannel("sftp"); // 打開SFTP通道
channel.connect(); // 建立SFTP通道的連接
LOG.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
+ ", returning: " + channel);
return (ChannelSftp) channel;
}
public void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
3、實(shí)例
import com.jcraft.jsch.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class SFTPDownloadWithRateLimit {
public static void main(String[] args) {
String host = "hostname";
String username = "username";
String password = "password";
String remoteFile = "/path/to/remote/file";
String localFile = "localFile";
int rateLimit = 1024; // 1KB/s
JSch jsch = new JSch();
try {
Session session = jsch.getSession(username, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// 設(shè)置下載速率限制
channelSftp.setInputStream(new BufferedInputStream(channelSftp.get(remoteFile), rateLimit));
InputStream inputStream = channelSftp.get(remoteFile);
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException | java.io.IOException e) {
e.printStackTrace();
}
}
}
或
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.FileOutputStream;
import java.io.InputStream;
public class SFTPDownloadWithRateLimit {
public static void main(String[] args) {
String host = "sftp.example.com";
String username = "username";
String password = "password";
int port = 22;
String remoteFilePath = "/path/to/remote/file";
String localFilePath = "/path/to/local/file";
int downloadRate = 1024; // 1 KB/s
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
InputStream inputStream = channelSftp.get(remoteFilePath);
FileOutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
long startTime = System.currentTimeMillis();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
long elapsedTime = System.currentTimeMillis() - startTime;
long expectedTime = (outputStream.getChannel().size() / downloadRate) * 1000;
if (elapsedTime < expectedTime) {
Thread.sleep(expectedTime - elapsedTime);
}
}
inputStream.close();
outputStream.close();
channelSftp.disconnect();
session.disconnect();
System.out.println("File downloaded successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面是根據(jù)指定速率進(jìn)行下載。
4、工具類
import com.jcraft.jsch.*;
import java.io.*;
public class SFTPUtil {
private String host;
private int port;
private String username;
private String password;
public SFTPUtil(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
public void uploadFile(String localFilePath, String remoteFilePath) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.put(new FileInputStream(localFilePath), remoteFilePath);
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException | FileNotFoundException e) {
e.printStackTrace();
}
}
public void downloadFile(String remoteFilePath, String localFilePath) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(remoteFilePath, new FileOutputStream(localFilePath));
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException | FileNotFoundException e) {
e.printStackTrace();
}
}
}JSch支持在文件傳輸時(shí)對(duì)傳輸進(jìn)度的監(jiān)控??梢詫?shí)現(xiàn)JSch提供的SftpProgressMonitor接口來完成這個(gè)功能。
- init(): 當(dāng)文件開始傳輸時(shí),調(diào)用init方法。
- count(): 當(dāng)每次傳輸了一個(gè)數(shù)據(jù)塊后,調(diào)用count方法,count方法的參數(shù)為這一次傳輸?shù)臄?shù)據(jù)塊大小。
- end(): 當(dāng)傳輸結(jié)束時(shí),調(diào)用end方法。
public class MyProgressMonitor implements SftpProgressMonitor {
private long transfered;
@Override
public boolean count(long count) {
transfered = transfered + count;
System.out.println("Currently transferred total size: " + transfered + " bytes");
return true;
}
@Override
public void end() {
System.out.println("Transferring done.");
}
@Override
public void init(int op, String src, String dest, long max) {
System.out.println("Transferring begin.");
}
}到此這篇關(guān)于Java中通過sftp協(xié)議實(shí)現(xiàn)上傳下載的示例代碼的文章就介紹到這了,更多相關(guān)Java sftp上傳下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在IDEA中安裝MyBatis Log Plugin插件,執(zhí)行mybatis的sql語句(推薦)
這篇文章主要介紹了在IDEA中安裝MyBatis Log Plugin插件,執(zhí)行mybatis的sql語句,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
springboot如何使用thymeleaf模板訪問html頁面
springboot中推薦使用thymeleaf模板,使用html作為頁面展示。那么如何通過Controller來訪問來訪問html頁面呢?下面通過本文給大家詳細(xì)介紹,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05
Java虛擬機(jī)JVM優(yōu)化實(shí)戰(zhàn)的過程全記錄
有人說Java之所以能夠崛起,JVM功不可沒。Java虛擬機(jī)最初服務(wù)于讓Java語言凌駕于平臺(tái)之上,實(shí)現(xiàn)“編寫一次,到處運(yùn)行”,那么下面這篇文章主要給大家分享了個(gè)關(guān)于Java虛擬機(jī)JVM優(yōu)化實(shí)戰(zhàn)的過程全記錄,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08
解決spring.thymeleaf.cache=false不起作用的問題
這篇文章主要介紹了解決spring.thymeleaf.cache=false不起作用的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot(cloud)自動(dòng)裝配bean找不到類型的問題
這篇文章主要介紹了SpringBoot(cloud)自動(dòng)裝配bean找不到類型的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java中的ArrayList(擴(kuò)容機(jī)制)詳解
ArrayList作為Java中廣泛使用的動(dòng)態(tài)數(shù)組,其擴(kuò)容機(jī)制是保證性能和內(nèi)存使用平衡的關(guān)鍵,默認(rèn)初始容量為10,擴(kuò)容因子為1.5,旨在減少頻繁的內(nèi)存分配和數(shù)據(jù)遷移代價(jià),同時(shí)建議使用預(yù)估計(jì)的初始化容量以減少擴(kuò)容次數(shù)2024-11-11
mybatis 自定義實(shí)現(xiàn)攔截器插件Interceptor示例
這篇文章主要介紹了mybatis 自定義實(shí)現(xiàn)攔截器插件Interceptor,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
通過實(shí)例講解springboot整合WebSocket
這篇文章主要介紹了通過實(shí)例講解springboot整合WebSocket,WebSocket為游覽器和服務(wù)器提供了雙工異步通信的功能,即游覽器可以向服務(wù)器發(fā)送消息,服務(wù)器也可以向游覽器發(fā)送消息。,需要的朋友可以參考下2019-06-06

