這篇文章運用簡單易懂的例子給大家介紹使用Java8如何實現FTP及SFTP文件的上傳下載,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
一般連接windows服務器使用FTP,連接linux服務器使用SFTP。linux都是通過SFTP上傳文件,不需要額外安裝,非要使用FTP的話,還得安裝FTP服務(雖然剛開始我就是這么干的)。
另外就是jdk1.8和jdk1.7之前的方法有些不同,網上有很多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) { //把遠程系統上的目錄切換到參數path所指定的目錄 ftpClient.changeDirectory(path); } } catch (FtpProtocolException e) { e.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } /** * 關閉連接 */ 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的整個調用過程,這個過程就是通過Ip、Port、Username、Password獲取一個Session, * 然后通過Session打開SFTP通道(獲得SFTP Channel對象),再在建立通道(Channel)連接,最后我們就是 * 通過這個Channel對象來調用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; // 創建JSch對象 JSch jsch = new JSch(); // 根據用戶名,主機ip,端口獲取一個Session對象 session = jsch.getSession(ftpUserName, ftpHost, ftpPort); if (ftpPassword != null) { // 設置密碼 session.setPassword(ftpPassword); } Properties configTemp = new Properties(); configTemp.put("StrictHostKeyChecking", "no"); // 為Session對象設置properties session.setConfig(configTemp); // 設置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實現SFTP核心類,它包含了所有SFTP的方法,如:
文件上傳put(),
文件下載get(),
進入指定目錄cd().
得到指定目錄下的文件列表ls().
重命名指定文件或目錄rename().
刪除指定文件rm(),創建目錄mkdir(),刪除目錄rmdir().
大家引用方法時可以快速參考一下,具體傳參需參考源碼~
最后還要提一下的就是JSch支持的三種文件傳輸模式:
● APPEND 追加模式,如果目標文件已存在,傳輸的文件將在目標文件后追加。
● RESUME 恢復模式,如果文件已經傳輸一部分,這時由于網絡或其他任何原因導致文件傳輸中斷,如果下一次傳輸相同的文件,則會從上一次中斷的地方續傳。
● OVERWRITE 完全覆蓋模式,這是JSch的默認文件傳輸模式,即如果目標文件已經存在,傳輸的文件將完全覆蓋目標文件,產生新的文件。
FTP和SFTP區別
FTP是一種文件傳輸協議,一般是為了方便數據共享的。包括一個FTP服務器和多個FTP客戶端。FTP客戶端通過FTP協議在服務器上下載資源。而SFTP協議是在FTP的基礎上對數據進行加密,使得傳輸的數據相對來說更安全。但是這種安全是以犧牲效率為代價的,也就是說SFTP的傳輸效率比FTP要低(不過現實使用當中,沒有發現多大差別)。個人膚淺的認為就是:一;FTP要安裝,SFTP不要安裝。二;SFTP更安全,但更安全帶來副作用就是的效率比FTP要低些。
建議使用sftp代替ftp。
主要因為:
1、可以不用額外安裝任何服務器端程序
2、會更省系統資源。
3、SFTP使用加密傳輸認證信息和傳輸數據,相對來說會更安全。
4、也不需要單獨配置,對新手來說比較簡單(開啟SSH默認就開啟了SFTP)。
關于使用Java8如何實現FTP及SFTP文件的上傳下載就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。