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要低得多,如果您對網(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對象,即ChannelSftp的實(shí)例對象,在應(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ù)用戶名,主機(jī)ip,端口獲取一個(gè)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時(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í)對傳輸進(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Cloud Gateway 獲取請求體(Request Body)的多種方法
這篇文章主要介紹了Spring Cloud Gateway 獲取請求體(Request Body)的多種方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Java 實(shí)戰(zhàn)范例之線上新聞平臺(tái)系統(tǒng)的實(shí)現(xiàn)
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+jsp+jdbc+mysql實(shí)現(xiàn)一個(gè)線上新聞平臺(tái)系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2021-11-11Java實(shí)現(xiàn)圖片上傳至服務(wù)器功能(FTP協(xié)議)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)圖片上傳至服務(wù)器功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06java開發(fā)分布式服務(wù)框架Dubbo暴露服務(wù)過程詳解
這篇文章主要為大家介紹了java開發(fā)分布式服務(wù)框架Dubbo暴露服務(wù)的過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11SpringBoot實(shí)現(xiàn)發(fā)送短信的示例代碼
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)發(fā)送短信的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Java使用poi導(dǎo)出ppt文件的實(shí)現(xiàn)代碼
Apache POI 是用Java編寫的免費(fèi)開源的跨平臺(tái)的 Java API,Apache POI提供API給Java對Microsoft Office格式檔案讀和寫的功能。本文給大家介紹Java使用poi導(dǎo)出ppt文件的實(shí)現(xiàn)代碼,需要的朋友參考下吧2021-06-06