java搭建ftp/sftp進行數據傳遞的全過程
ftp/sftp概念及搭建
ftp是一種文件傳輸協議,讓客戶端和服務端能夠互相傳遞文件,圖片等數據;方便快捷;
sftp是ssh file transfer protocol縮寫,也是一種文件傳輸協議.sftp比ftp安全的多,但傳輸效率要低的多
搭建:
ftp可以搜索網上教程,很多,在此不過多贅述
創建完成後,通過瀏覽器就可以訪問到內容瞭;
sftp用freesshd搭建(記得freesshd的安裝路徑不要有中文,否則各種報錯);這個也可以自行百度,解決方法很多;
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 服務器地址IP地址 private static int port; // FTP 端口 //構造函數初始化 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 客戶端代理 /** * 連接到服務器 * @return true 連接服務器成功,false 連接服務器失敗 */ public boolean connectServer() { System.out.println("進行連接"); boolean flag = true; if (ftpClient == null) { int reply; try { System.out.println("初始化連接"); ftpClient = new FTPClient(); String LOCAL_CHARSET = "GBK"; System.out.println("設置IP和端口"); ftpClient.connect(ip, port); System.out.println("設置密碼"); ftpClient.login(userName, password); System.out.println("進行連接"); reply = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); System.out.println("設置編碼操作方式"); if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // 開啟服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK). { LOCAL_CHARSET = "UTF-8"; } System.out.println("設置編碼操作方式1"); ftpClient.setControlEncoding(LOCAL_CHARSET); System.out.println("是否連接成功"); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.out.println("FTP 服務拒絕連接!"); flag = false; } } catch (SocketException e) { flag = false; e.printStackTrace(); System.out.println("登錄ftp服務器 " + ip + " 失敗,連接超時!"); } catch (IOException e) { flag = false; e.printStackTrace(); System.out.println("登錄ftp服務器 " + ip + " 失敗,FTP服務器無法打開!"); } catch (Exception e) { flag = false; e.printStackTrace(); // System.out.println("登錄ftp服務器 " + ip + " 失敗,FTP服務器無法打開!"); } } return flag; } /** * 上傳文件 * * @param remoteFile 遠程文件路徑,支持多級目錄嵌套 需要保證路徑已經存在 並切包含文件重命名 * @param localFile 本地文件名稱,絕對路徑 * */ 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; } /** * 上傳單個文件 * * @param local 本地文件名稱,絕對路徑 * @param remote 遠程文件路徑,支持多級目錄嵌套 * @return */ public boolean uploadFile(String local, String remote) { boolean flag = true; String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); // 創建服務器遠程目錄結構,創建失敗直接返回 if (!CreateDirecroty(remote)) { return false; } } File f = new File(local); if (!uploadFile(remoteFileName, f)) { flag = false; } return flag; } /** * 上傳文件夾內的所有文件 * * * @param filename 本地文件夾絕對路徑 隻能上傳文件,子文件夾無法上傳 * @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; // 上傳失敗的文件個數 int m = 0; // 上傳成功的文件個數 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("失敗個數" + n); l.add("成功個數" + 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 --服務器上的文件名 * @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; } /** * 刪除一個文件 */ 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服務器上的所有文件和目錄 */ 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; } /** * 關閉連接 */ public void closeConnect() { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); ftpClient=null; } } catch (Exception e) { e.printStackTrace(); } } /** * 設置傳輸文件的類型[文本文件或者二進制文件] 1是文本文件 其餘 二進制文件 * * @param fileType--BINARY_FILE_TYPE(二進制文件)、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(); } } /** * 進入到服務器的某個目錄下 * * @param directory */ public boolean changeWorkingDirectory(String directory) { boolean flag = true; try { flag = ftpClient.changeWorkingDirectory(directory); if (flag) { System.out.println("進入文件夾" + directory + " 成功!"); } else { System.out.println("進入文件夾" + 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(); } } /** * 設置FTP客服端的配置--一般可以不設置 * * @return ftpConfig */ @SuppressWarnings("unused") private FTPClientConfig getFtpConfig() { FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); return ftpConfig; } /** * 轉碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉碼 * * @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 ""; } } /** * 在服務器上創建一個文件夾 * * @param dir 文件夾名稱,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... */ public boolean makeDirectory(String dir) { boolean flag = true; try { flag = ftpClient.makeDirectory(dir); if (flag) { System.out.println("創建文件夾" + dir + " 成功!"); } else { System.out.println("創建文件夾" + dir + " 失敗!"); } } catch (Exception e) { e.printStackTrace(); } return flag; } /** * 遞歸創建遠程服務器目錄 * * @param remote 遠程服務器文件絕對路徑 路徑: /Draw1/Point1/GUID1/a.bmp 或者/Draw1/Point1/GUID1/ 最後一級文件夾必須有/否則最後一級文件夾創建不成功 * * @return 目錄創建是否成功 * @throws IOException */ public boolean CreateDirecroty(String remote) { boolean success = true; try { String directory = remote.substring(0, remote.lastIndexOf("/") + 1); // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄 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("創建目錄[" + subDirectory + "]失敗"); System.out.println("創建目錄[" + subDirectory + "]失敗"); success = false; return success; } } start = end + 1; end = directory.indexOf("/", start); // 檢查所有目錄是否創建完畢 if (end <= start) { break; } } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } }
ftp測試代碼如下:
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(); } }
輸出結果如下:
成功瞭;
sftp搭建完成後,也測試下,至於搭建過程,自行百度好啦
看到沒,連接成功瞭;我用我的電腦模擬的;