Java中通過sftp協(xié)議實現(xiàn)上傳下載的示例代碼
在java開發(fā)中,遇到需要將linux系統(tǒng)中指定目錄下的文件下載到windows本地的需求,下面聊聊通過sftp協(xié)議實現(xiàn)上傳和下載。
1、SFTP協(xié)議
JSch是Java Secure Channel的縮寫。JSch是一個SSH2的純Java實現(xiàn)。它允許你連接到一個SSH服務(wù)器,并且可以使用端口轉(zhuǎn)發(fā),X11轉(zhuǎn)發(fā),文件傳輸?shù)?,?dāng)然你也可以集成它的功能到你自己的應(yīng)用程序。
SFTP是Secure File Transfer Protocol的縮寫,安全文件傳送協(xié)議??梢詾閭鬏斘募峁┮环N安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務(wù)器的安全方式。SFTP是使用加密傳輸認證信息和傳輸?shù)臄?shù)據(jù),所以,使用SFTP是非常安全的。但是,由于這種傳輸方式使用了加密/解密技術(shù),所以傳輸效率比普通的FTP要低得多,如果您對網(wǎng)絡(luò)安全性要求更高時,可以使用SFTP代替FTP。
2、SFTP核心類
ChannelSftp類是JSch實現(xiàn)SFTP核心類,它包含了所有SFTP的方法,如:
- put(): 文件上傳
- get(): 文件下載
- cd(): 進入指定目錄
- ls(): 得到指定目錄下的文件列表
- rename(): 重命名指定文件或目錄
- rm(): 刪除指定文件
- mkdir(): 創(chuàng)建目錄
- rmdir(): 刪除目錄
其他參加源碼。
JSch支持三種文件傳輸模式: - OVERWRITE 完全覆蓋模式,這是JSch的默認文件傳輸模式,即如果目標(biāo)文件已經(jīng)存在,傳輸?shù)奈募⑼耆采w目標(biāo)文件,產(chǎn)生新的文件。
- RESUME 恢復(fù)模式,如果文件已經(jīng)傳輸一部分,這時由于網(wǎng)絡(luò)或其他任何原因?qū)е挛募鬏斨袛?,如果下一次傳輸相同的文件,則會從上一次中斷的地方續(xù)傳。
- APPEND 追加模式,如果目標(biāo)文件已存在,傳輸?shù)奈募⒃谀繕?biāo)文件后追加。
編寫一個工具類,根據(jù)ip,用戶名及密碼得到一個SFTP channel對象,即ChannelSftp的實例對象,在應(yīng)用程序中就可以使用該對象來調(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對象
session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據(jù)用戶名,主機ip,端口獲取一個Session對象
LOG.debug("Session created.");
if (ftpPassword != null) {
session.setPassword(ftpPassword); // 設(shè)置密碼
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 為Session對象設(shè)置properties
session.setTimeout(timeout); // 設(shè)置timeout時間
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、實例
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ù)指定速率進行下載。
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支持在文件傳輸時對傳輸進度的監(jiān)控??梢詫崿F(xiàn)JSch提供的SftpProgressMonitor接口來完成這個功能。
- init(): 當(dāng)文件開始傳輸時,調(diào)用init方法。
- count(): 當(dāng)每次傳輸了一個數(shù)據(jù)塊后,調(diào)用count方法,count方法的參數(shù)為這一次傳輸?shù)臄?shù)據(jù)塊大小。
- end(): 當(dāng)傳輸結(jié)束時,調(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é)議實現(xiàn)上傳下載的示例代碼的文章就介紹到這了,更多相關(guān)Java sftp上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在IDEA中安裝MyBatis Log Plugin插件,執(zhí)行mybatis的sql語句(推薦)
這篇文章主要介紹了在IDEA中安裝MyBatis Log Plugin插件,執(zhí)行mybatis的sql語句,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
springboot如何使用thymeleaf模板訪問html頁面
springboot中推薦使用thymeleaf模板,使用html作為頁面展示。那么如何通過Controller來訪問來訪問html頁面呢?下面通過本文給大家詳細介紹,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05
Java虛擬機JVM優(yōu)化實戰(zhàn)的過程全記錄
有人說Java之所以能夠崛起,JVM功不可沒。Java虛擬機最初服務(wù)于讓Java語言凌駕于平臺之上,實現(xiàn)“編寫一次,到處運行”,那么下面這篇文章主要給大家分享了個關(guān)于Java虛擬機JVM優(yōu)化實戰(zhàn)的過程全記錄,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08
解決spring.thymeleaf.cache=false不起作用的問題
這篇文章主要介紹了解決spring.thymeleaf.cache=false不起作用的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot(cloud)自動裝配bean找不到類型的問題
這篇文章主要介紹了SpringBoot(cloud)自動裝配bean找不到類型的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
mybatis 自定義實現(xiàn)攔截器插件Interceptor示例
這篇文章主要介紹了mybatis 自定義實現(xiàn)攔截器插件Interceptor,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

