有網(wǎng)上的代碼,也有自己的理解,代碼備份
一般連接windows服務(wù)器使用FTP,連接linux服務(wù)器使用SFTP。linux都是通過SFTP上傳文件,不需要額外安裝,非要使用FTP的話,還得安裝FTP服務(wù)(雖然剛開始我就是這么干的)。
另外就是jdk1.8和jdk1.7之前的方法有些不同,網(wǎng)上有很多jdk1.7之前的介紹,本篇是jdk1.8的
添加依賴Jsch-0.1.54.jar
1
2
3
4
5
6
|
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> < dependency > < groupId >com.jcraft</ groupId > < artifactId >jsch</ artifactId > < version >0.1.54</ version > </ dependency > |
FTP上傳下載文件例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
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服務(wù)器 */ 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 { /* ******連接服務(wù)器的兩種方法*******/ 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 遠程文件路徑(服務(wù)器端) * @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上傳下載文件例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
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服務(wù)器 */ 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ù)奈募⒃谀繕宋募笞芳印?/p>
● RESUME 恢復模式,如果文件已經(jīng)傳輸一部分,這時由于網(wǎng)絡(luò)或其他任何原因?qū)е挛募鬏斨袛啵绻乱淮蝹鬏斚嗤奈募瑒t會從上一次中斷的地方續(xù)傳。
● OVERWRITE 完全覆蓋模式,這是JSch的默認文件傳輸模式,即如果目標文件已經(jīng)存在,傳輸?shù)奈募⑼耆采w目標文件,產(chǎn)生新的文件。
FTP和SFTP區(qū)別
FTP是一種文件傳輸協(xié)議,一般是為了方便數(shù)據(jù)共享的。包括一個FTP服務(wù)器和多個FTP客戶端。FTP客戶端通過FTP協(xié)議在服務(wù)器上下載資源。而SFTP協(xié)議是在FTP的基礎(chǔ)上對數(shù)據(jù)進行加密,使得傳輸?shù)臄?shù)據(jù)相對來說更安全。但是這種安全是以犧牲效率為代價的,也就是說SFTP的傳輸效率比FTP要低(不過現(xiàn)實使用當中,沒有發(fā)現(xiàn)多大差別)。個人膚淺的認為就是:一;FTP要安裝,SFTP不要安裝。二;SFTP更安全,但更安全帶來副作用就是的效率比FTP要低些。
建議使用sftp代替ftp。
主要因為:
1、可以不用額外安裝任何服務(wù)器端程序
2、會更省系統(tǒng)資源。
3、SFTP使用加密傳輸認證信息和傳輸數(shù)據(jù),相對來說會更安全。
4、也不需要單獨配置,對新手來說比較簡單(開啟SSH默認就開啟了SFTP)。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/acm-bingzi/p/java8-ftp-sftp.html