Java8實現(xiàn)FTP及SFTP文件上傳下載
有網(wǎng)上的代碼,也有自己的理解,代碼備份
一般連接windows服務器使用FTP,連接linux服務器使用SFTP。linux都是通過SFTP上傳文件,不需要額外安裝,非要使用FTP的話,還得安裝FTP服務(雖然剛開始我就是這么干的)。
另外就是jdk1.8和jdk1.7之前的方法有些不同,網(wǎng)上有很多jdk1.7之前的介紹,本篇是jdk1.8的
添加依賴Jsch-0.1.54.jar
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
FTP上傳下載文件例子
import sun.net.ftp.FtpClient; import sun.net.ftp.FtpProtocolException; import java.io.*; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Java自帶的API對FTP的操作 */ public class Test { private FtpClient ftpClient; Test(){ /* 使用默認的端口號、用戶名、密碼以及根目錄連接FTP服務器 */ this.connectServer("192.168.56.130", 21, "jiashubing", "123456", "/home/jiashubing/ftp/anonymous/"); } public void connectServer(String ip, int port, String user, String password, String path) { try { /* ******連接服務器的兩種方法*******/ ftpClient = FtpClient.create(); try { SocketAddress addr = new InetSocketAddress(ip, port); ftpClient.connect(addr); ftpClient.login(user, password.toCharArray()); System.out.println("login success!"); if (path.length() != 0) { //把遠程系統(tǒng)上的目錄切換到參數(shù)path所指定的目錄 ftpClient.changeDirectory(path); } } catch (FtpProtocolException e) { e.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } /** * 關(guān)閉連接 */ public void closeConnect() { try { ftpClient.close(); System.out.println("disconnect success"); } catch (IOException ex) { System.out.println("not disconnect"); ex.printStackTrace(); throw new RuntimeException(ex); } } /** * 上傳文件 * @param localFile 本地文件 * @param remoteFile 遠程文件 */ public void upload(String localFile, String remoteFile) { File file_in = new File(localFile); try(OutputStream os = ftpClient.putFileStream(remoteFile); FileInputStream is = new FileInputStream(file_in)) { byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } System.out.println("upload success"); } catch (IOException ex) { System.out.println("not upload"); ex.printStackTrace(); } catch (FtpProtocolException e) { e.printStackTrace(); } } /** * 下載文件。獲取遠程機器上的文件filename,借助TelnetInputStream把該文件傳送到本地。 * @param remoteFile 遠程文件路徑(服務器端) * @param localFile 本地文件路徑(客戶端) */ public void download(String remoteFile, String localFile) { File file_in = new File(localFile); try(InputStream is = ftpClient.getFileStream(remoteFile); FileOutputStream os = new FileOutputStream(file_in)){ byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } System.out.println("download success"); } catch (IOException ex) { System.out.println("not download"); ex.printStackTrace(); }catch (FtpProtocolException e) { e.printStackTrace(); } } public static void main(String agrs[]) { Test fu = new Test(); //下載測試 String filepath[] = {"aa.xlsx","bb.xlsx"}; String localfilepath[] = {"E:/lalala/aa.xlsx","E:/lalala/bb.xlsx"}; for (int i = 0; i < filepath.length; i++) { fu.download(filepath[i], localfilepath[i]); } //上傳測試 String localfile = "E:/lalala/tt.xlsx"; String remotefile = "tt.xlsx"; //上傳 fu.upload(localfile, remotefile); fu.closeConnect(); } }
SFTP上傳下載文件例子
import com.jcraft.jsch.*; import java.util.Properties; /** * 解釋一下SFTP的整個調(diào)用過程,這個過程就是通過Ip、Port、Username、Password獲取一個Session, * 然后通過Session打開SFTP通道(獲得SFTP Channel對象),再在建立通道(Channel)連接,最后我們就是 * 通過這個Channel對象來調(diào)用SFTP的各種操作方法.總是要記得,我們操作完SFTP需要手動斷開Channel連接與Session連接。 * @author jiashubing * @since 2018/5/8 */ public class SftpCustom { private ChannelSftp channel; private Session session; private String sftpPath; SftpCustom() { /* 使用端口號、用戶名、密碼以連接SFTP服務器 */ this.connectServer("192.168.56.130", 22, "jiashubing", "123456", "/home/ftp/"); } SftpCustom(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) { this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath); } public void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) { try { this.sftpPath = sftpPath; // 創(chuàng)建JSch對象 JSch jsch = new JSch(); // 根據(jù)用戶名,主機ip,端口獲取一個Session對象 session = jsch.getSession(ftpUserName, ftpHost, ftpPort); if (ftpPassword != null) { // 設(shè)置密碼 session.setPassword(ftpPassword); } Properties configTemp = new Properties(); configTemp.put("StrictHostKeyChecking", "no"); // 為Session對象設(shè)置properties session.setConfig(configTemp); // 設(shè)置timeout時間 session.setTimeout(60000); session.connect(); // 通過Session建立鏈接 // 打開SFTP通道 channel = (ChannelSftp) session.openChannel("sftp"); // 建立SFTP通道的連接 channel.connect(); } catch (JSchException e) { //throw new RuntimeException(e); } } /** * 斷開SFTP Channel、Session連接 */ public void closeChannel() { try { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } catch (Exception e) { // } } /** * 上傳文件 * * @param localFile 本地文件 * @param remoteFile 遠程文件 */ public void upload(String localFile, String remoteFile) { try { remoteFile = sftpPath + remoteFile; channel.put(localFile, remoteFile, ChannelSftp.OVERWRITE); channel.quit(); } catch (SftpException e) { //e.printStackTrace(); } } /** * 下載文件 * * @param remoteFile 遠程文件 * @param localFile 本地文件 */ public void download(String remoteFile, String localFile) { try { remoteFile = sftpPath + remoteFile; channel.get(remoteFile, localFile); channel.quit(); } catch (SftpException e) { //e.printStackTrace(); } } public static void main(String[] args) { SftpCustom sftpCustom = new SftpCustom(); //上傳測試 String localfile = "E:/lalala/tt.xlsx"; String remotefile = "/home/ftp/tt2.xlsx"; sftpCustom.upload(localfile, remotefile); //下載測試 sftpCustom.download(remotefile, "E:/lalala/tt3.xlsx"); sftpCustom.closeChannel(); } }
Jsch-0.1.54.jar 學習了解
ChannelSftp類是JSch實現(xiàn)SFTP核心類,它包含了所有SFTP的方法,如:
文件上傳put(),
文件下載get(),
進入指定目錄cd().
得到指定目錄下的文件列表ls().
重命名指定文件或目錄rename().
刪除指定文件rm(),創(chuàng)建目錄mkdir(),刪除目錄rmdir().
大家引用方法時可以快速參考一下,具體傳參需參考源碼~
最后還要提一下的就是JSch支持的三種文件傳輸模式:
● APPEND 追加模式,如果目標文件已存在,傳輸?shù)奈募⒃谀繕宋募笞芳印?br />
● RESUME 恢復模式,如果文件已經(jīng)傳輸一部分,這時由于網(wǎng)絡(luò)或其他任何原因?qū)е挛募鬏斨袛啵绻乱淮蝹鬏斚嗤奈募?,則會從上一次中斷的地方續(xù)傳。
● OVERWRITE 完全覆蓋模式,這是JSch的默認文件傳輸模式,即如果目標文件已經(jīng)存在,傳輸?shù)奈募⑼耆采w目標文件,產(chǎn)生新的文件。
FTP和SFTP區(qū)別
FTP是一種文件傳輸協(xié)議,一般是為了方便數(shù)據(jù)共享的。包括一個FTP服務器和多個FTP客戶端。FTP客戶端通過FTP協(xié)議在服務器上下載資源。而SFTP協(xié)議是在FTP的基礎(chǔ)上對數(shù)據(jù)進行加密,使得傳輸?shù)臄?shù)據(jù)相對來說更安全。但是這種安全是以犧牲效率為代價的,也就是說SFTP的傳輸效率比FTP要低(不過現(xiàn)實使用當中,沒有發(fā)現(xiàn)多大差別)。個人膚淺的認為就是:一;FTP要安裝,SFTP不要安裝。二;SFTP更安全,但更安全帶來副作用就是的效率比FTP要低些。
建議使用sftp代替ftp。
主要因為:
1、可以不用額外安裝任何服務器端程序
2、會更省系統(tǒng)資源。
3、SFTP使用加密傳輸認證信息和傳輸數(shù)據(jù),相對來說會更安全。
4、也不需要單獨配置,對新手來說比較簡單(開啟SSH默認就開啟了SFTP)。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringMVC五大組件與執(zhí)行原理分析總結(jié)
這篇文章主要介紹了SpringMVC五大組件與執(zhí)行原理分析總結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-01-01java模擬http的Get/Post請求,并設(shè)置ip與port代理的方法
下面小編就為大家?guī)硪黄猨ava模擬http的Get/Post請求,并設(shè)置ip與port代理的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02Quartz實現(xiàn)JAVA定時任務的動態(tài)配置的方法
這篇文章主要介紹了Quartz實現(xiàn)JAVA定時任務的動態(tài)配置的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07Java面試題及答案集錦(基礎(chǔ)題122道,代碼題19道)
本文是小編收集整理的關(guān)于java基礎(chǔ)面試題及答案集錦,基礎(chǔ)題目有122道,代碼題目有19道,非常不錯,值得收藏,需要的朋友參考下2017-01-01關(guān)于mybatis plus 中的查詢優(yōu)化問題
這篇文章主要介紹了關(guān)于mybatis plus 中的查詢優(yōu)化問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01