java搭建ftp/sftp進(jìn)行數(shù)據(jù)傳遞的全過(guò)程
ftp/sftp概念及搭建
ftp是一種文件傳輸協(xié)議,讓客戶端和服務(wù)端能夠互相傳遞文件,圖片等數(shù)據(jù);方便快捷;
sftp是ssh file transfer protocol縮寫(xiě),也是一種文件傳輸協(xié)議.sftp比f(wàn)tp安全的多,但傳輸效率要低的多
搭建:
ftp可以搜索網(wǎng)上教程,很多,在此不過(guò)多贅述
創(chuàng)建完成后,通過(guò)瀏覽器就可以訪問(wèn)到內(nèi)容了;
sftp用freesshd搭建(記得freesshd的安裝路徑不要有中文,否則各種報(bào)錯(cuò));這個(gè)也可以自行百度,解決方法很多;
Java代碼
代碼如下: import java.io.*; import java.net.SocketException; import java.util.ArrayList; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; public class FTPClientTest { private static String userName; // FTP 登錄用戶名 private static String password; // FTP 登錄密碼 private static String ip;// FTP 服務(wù)器地址IP地址 private static int port; // FTP 端口 //構(gòu)造函數(shù)初始化 public FTPClientTest(String userName,String password,String ip,int port){ this.userName=userName; this.password=password; this.ip=ip; this.port=port; } public static String getUserName(){ return userName;} public static void setUserName(String userName) {FTPClientTest.userName = userName; } public static String getPassword() {return password;} public static void setPassword(String password){FTPClientTest.password = password;} public static String getIp() { return ip; } public static void setIp(String ip){FTPClientTest.ip = ip;} public static int getPort() {return port; } public static void setPort(int port) {FTPClientTest.port = port;} private static FTPClient ftpClient = null; // FTP 客戶端代理 /** * 連接到服務(wù)器 * @return true 連接服務(wù)器成功,false 連接服務(wù)器失敗 */ public boolean connectServer() { System.out.println("進(jìn)行連接"); boolean flag = true; if (ftpClient == null) { int reply; try { System.out.println("初始化連接"); ftpClient = new FTPClient(); String LOCAL_CHARSET = "GBK"; System.out.println("設(shè)置IP和端口"); ftpClient.connect(ip, port); System.out.println("設(shè)置密碼"); ftpClient.login(userName, password); System.out.println("進(jìn)行連接"); reply = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); System.out.println("設(shè)置編碼操作方式"); if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // 開(kāi)啟服務(wù)器對(duì)UTF-8的支持,如果服務(wù)器支持就用UTF-8編碼,否則就使用本地編碼(GBK). { LOCAL_CHARSET = "UTF-8"; } System.out.println("設(shè)置編碼操作方式1"); ftpClient.setControlEncoding(LOCAL_CHARSET); System.out.println("是否連接成功"); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.out.println("FTP 服務(wù)拒絕連接!"); flag = false; } } catch (SocketException e) { flag = false; e.printStackTrace(); System.out.println("登錄ftp服務(wù)器 " + ip + " 失敗,連接超時(shí)!"); } catch (IOException e) { flag = false; e.printStackTrace(); System.out.println("登錄ftp服務(wù)器 " + ip + " 失敗,F(xiàn)TP服務(wù)器無(wú)法打開(kāi)!"); } catch (Exception e) { flag = false; e.printStackTrace(); // System.out.println("登錄ftp服務(wù)器 " + ip + " 失敗,F(xiàn)TP服務(wù)器無(wú)法打開(kāi)!"); } } return flag; } /** * 上傳文件 * * @param remoteFile 遠(yuǎn)程文件路徑,支持多級(jí)目錄嵌套 需要保證路徑已經(jīng)存在 并切包含文件重命名 * @param localFile 本地文件名稱,絕對(duì)路徑 * */ public boolean uploadFile(String remoteFile1, File localFile) { boolean flag = false; try { InputStream in = new FileInputStream(localFile); String remote = new String(remoteFile1.getBytes("UTF-8"), "iso-8859-1"); if (ftpClient.storeFile(remote, in)) { flag = true; System.out.println(localFile.getAbsolutePath() + "上傳文件成功!"); } else { System.out.println(localFile.getAbsolutePath() + "上傳文件失敗!"); } in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } /** * 上傳單個(gè)文件 * * @param local 本地文件名稱,絕對(duì)路徑 * @param remote 遠(yuǎn)程文件路徑,支持多級(jí)目錄嵌套 * @return */ public boolean uploadFile(String local, String remote) { boolean flag = true; String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); // 創(chuàng)建服務(wù)器遠(yuǎn)程目錄結(jié)構(gòu),創(chuàng)建失敗直接返回 if (!CreateDirecroty(remote)) { return false; } } File f = new File(local); if (!uploadFile(remoteFileName, f)) { flag = false; } return flag; } /** * 上傳文件夾內(nèi)的所有文件 * * * @param filename 本地文件夾絕對(duì)路徑 只能上傳文件,子文件夾無(wú)法上傳 * @param uploadpath 上傳到FTP的路徑,形式為/或/dir1/dir2/../ * @return true 上傳成功,false 上傳失敗 * @throws IOException */ public ArrayList<String> uploadManyFile(String filename, String uploadpath) { boolean flag = true; ArrayList<String> l = new ArrayList<String>(); StringBuffer strBuf = new StringBuffer(); int n = 0; // 上傳失敗的文件個(gè)數(shù) int m = 0; // 上傳成功的文件個(gè)數(shù) try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.changeWorkingDirectory("/"); File file = new File(filename); File fileList[] = file.listFiles(); for (File upfile : fileList) { if (!upfile.isDirectory()) { String local = upfile.getCanonicalPath().replaceAll("\\\\", "/"); String temp = upfile.getCanonicalPath(); String a = temp.replace(filename + "\\", ""); String remote = uploadpath.replaceAll("\\\\", "/") + a; flag = uploadFile(local, remote); ftpClient.changeWorkingDirectory("/"); } if (!flag) { n++; strBuf.append(upfile.getName() + ","); System.out.println("文件[" + upfile.getName() + "]上傳失敗"); } else { m++; } } l.add("失敗個(gè)數(shù)" + n); l.add("成功個(gè)數(shù)" + m); l.add(strBuf.toString()); } catch (NullPointerException e) { e.printStackTrace(); System.out.println("本地文件上傳失?。≌也坏缴蟼魑募?!" + e); } catch (Exception e) { e.printStackTrace(); System.out.println("本地文件上傳失?。? + e); } return l; } /** * 下載文件 * * @param remoteFileName --服務(wù)器上的文件名 * @param localFileName--本地文件名 * @return true 下載成功,false 下載失敗 */ public boolean loadFile(String remoteFileName, String localFileName) { boolean flag = true; // 下載文件 BufferedOutputStream buffOut = null; try { buffOut = new BufferedOutputStream(new FileOutputStream(localFileName)); flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), buffOut); } catch (Exception e) { e.printStackTrace(); System.out.println("本地文件下載失??!" + e); } finally { try { if (buffOut != null) buffOut.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } /** * 刪除一個(gè)文件 */ public boolean deleteFile(String filename) { boolean flag = true; try { flag = ftpClient.deleteFile(new String(filename.getBytes("UTF-8"), "iso-8859-1")); if (flag) { System.out.println("刪除文件" + filename + "成功!"); } else { System.out.println("刪除文件" + filename + "成功!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 刪除空目錄 */ public void deleteEmptyDirectory(String pathname) { try { ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"), "iso-8859-1")); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 列出Ftp服務(wù)器上的所有文件和目錄 */ public String[] listRemoteAllFiles() { try { String[] names = ftpClient.listNames(); for (int i = 0; i < names.length; i++) { System.out.println(names[i]); } return names; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 關(guān)閉連接 */ public void closeConnect() { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); ftpClient=null; } } catch (Exception e) { e.printStackTrace(); } } /** * 設(shè)置傳輸文件的類型[文本文件或者二進(jìn)制文件] 1是文本文件 其余 二進(jìn)制文件 * * @param fileType--BINARY_FILE_TYPE(二進(jìn)制文件)、ASCII_FILE_TYPE(文本文件) * */ public void setFileType(int fileType1) { try { int a = FTP.BINARY_FILE_TYPE; if (fileType1 == 1) { a = FTP.ASCII_FILE_TYPE; } ftpClient.setFileType(a); } catch (Exception e) { e.printStackTrace(); } } /** * 進(jìn)入到服務(wù)器的某個(gè)目錄下 * * @param directory */ public boolean changeWorkingDirectory(String directory) { boolean flag = true; try { flag = ftpClient.changeWorkingDirectory(directory); if (flag) { System.out.println("進(jìn)入文件夾" + directory + " 成功!"); } else { System.out.println("進(jìn)入文件夾" + directory + " 失??!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 返回到上一層目錄 */ public void changeToParentDirectory() { try { ftpClient.changeToParentDirectory(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 重命名文件 * * @param oldFileName --原文件名 * @param newFileName --新文件名 */ public void renameFile(String oldFileName, String newFileName) { try { System.out.println(oldFileName); System.out.println(newFileName); ftpClient.rename(new String(oldFileName.getBytes("UTF-8"), "iso-8859-1"), new String(newFileName.getBytes("UTF-8"), "iso-8859-1")); } catch (IOException ioe) { ioe.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } /** * 設(shè)置FTP客服端的配置--一般可以不設(shè)置 * * @return ftpConfig */ @SuppressWarnings("unused") private FTPClientConfig getFtpConfig() { FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); return ftpConfig; } /** * 轉(zhuǎn)碼[ISO-8859-1 -> GBK] 不同的平臺(tái)需要不同的轉(zhuǎn)碼 * * @param obj * @return "" */ @SuppressWarnings("unused") private String iso8859togbk(Object obj) { try { if (obj == null) return ""; else return new String(obj.toString().getBytes("iso-8859-1"), "GBK"); } catch (Exception e) { return ""; } } /** * 在服務(wù)器上創(chuàng)建一個(gè)文件夾 * * @param dir 文件夾名稱,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... */ public boolean makeDirectory(String dir) { boolean flag = true; try { flag = ftpClient.makeDirectory(dir); if (flag) { System.out.println("創(chuàng)建文件夾" + dir + " 成功!"); } else { System.out.println("創(chuàng)建文件夾" + dir + " 失??!"); } } catch (Exception e) { e.printStackTrace(); } return flag; } /** * 遞歸創(chuàng)建遠(yuǎn)程服務(wù)器目錄 * * @param remote 遠(yuǎn)程服務(wù)器文件絕對(duì)路徑 路徑: /Draw1/Point1/GUID1/a.bmp 或者/Draw1/Point1/GUID1/ 最后一級(jí)文件夾必須有/否則最后一級(jí)文件夾創(chuàng)建不成功 * * @return 目錄創(chuàng)建是否成功 * @throws IOException */ public boolean CreateDirecroty(String remote) { boolean success = true; try { String directory = remote.substring(0, remote.lastIndexOf("/") + 1); // 如果遠(yuǎn)程目錄不存在,則遞歸創(chuàng)建遠(yuǎn)程服務(wù)器目錄 if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) { int start = 0; int end = 0; if (directory.startsWith("/")) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory; subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); if (!changeWorkingDirectory(subDirectory)) { if (makeDirectory(subDirectory)) { changeWorkingDirectory(subDirectory); } else { System.out.println("創(chuàng)建目錄[" + subDirectory + "]失敗"); System.out.println("創(chuàng)建目錄[" + subDirectory + "]失敗"); success = false; return success; } } start = end + 1; end = directory.indexOf("/", start); // 檢查所有目錄是否創(chuàng)建完畢 if (end <= start) { break; } } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } }
ftp測(cè)試代碼如下:
public class test { public static void main(String[] args) { FTPClientTest ftp=new FTPClientTest("user", "548", "168.125.256.22", 21); boolean b=ftp.connectServer(); System.out.println(b); System.out.println(ftp.listRemoteAllFiles()); System.out.println(ftp.uploadFile("F:/home/b.txt", "/c.txt")); System.out.println(ftp.loadFile("/a.txt", "F:/home/b.txt")); ftp.closeConnect(); } }
輸出結(jié)果如下:
成功了;
sftp搭建完成后,也測(cè)試下,至于搭建過(guò)程,自行百度好啦
看到?jīng)],連接成功了;我用我的電腦模擬的;
相關(guān)文章
Hibernate validator使用以及自定義校驗(yàn)器注解
這篇文章主要介紹了Hibernate validator使用以及自定義校驗(yàn)器注解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01JAVA maven項(xiàng)目使用釘釘SDK獲取token、用戶
這篇文章主要介紹了JAVA maven項(xiàng)目使用釘釘SDK獲取token、用戶,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06MyBatis3源碼解析之如何獲取數(shù)據(jù)源詳解
用myBatis3與spring整合的時(shí)候,我們可以通過(guò)多種方式獲取數(shù)據(jù)源,下面這篇文章主要給大家介紹了關(guān)于MyBatis3源碼解析之如何獲取數(shù)據(jù)源的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06Spring MVC Controller返回值及異常的統(tǒng)一處理方法
這篇文章主要給大家介紹了關(guān)于Spring MVC Controller返回值及異常的統(tǒng)一處理方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Spring MVC具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Java線程安全的常用類_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
在集合框架中,有些類是線程安全的,這些都是jdk1.1中的出現(xiàn)的。在jdk1.2之后,就出現(xiàn)許許多多非線程安全的類。 下面是這些線程安全的同步的類2017-06-06springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式
這篇文章主要介紹了springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11Java基于IO流實(shí)現(xiàn)登錄和注冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了Java基于IO流實(shí)現(xiàn)登錄和注冊(cè)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04