這裏僅僅是對ftp工具類的簡單使用,不少東西還不是很瞭解。固然學以至用,先用到這裏吧。java
不少知識點是相互聯繫的,但願之後的例子中可以結合更多的知識點進行實例編寫,這樣也有助於知識的鞏固。服務器
下面是我本身項目中用到的代碼工具
/** * 下載pdf文件 */ public String downLoadPdf(String url,String contNo,String localPdfName){ String newUrl=""; String pathUrl="172.18.100.165"; //FTP服務器hostname int port=21;//FTP服務器端口 String username="shwasextt20\\ftp"; //FTP登陸帳號 String password="qwerty1!"; //FTP登陸密碼 String remotePath="/Imagedownload";//FTP服務器上的相對路徑 String fileName;//要下載的文件名 // String localPath="I:\\2015\\workspace\\workspace_newng\\wj\\WebContent\\wwwroot\\ng\\downLoad";//下載後保存到本地的路徑 String localPath="C:\\project\\b2c\\cms.ear\\cms.war\\wwwroot\\ng\\downLoad";//下載後保存到本地的路徑 // String localPath="C:\\B2C\\cms.ear\\cms.war\\wwwroot\\ng\\downLoad";//下載後保存到本地的路徑 String localName = ""; Date date = new Date(); SimpleDateFormat dr = new SimpleDateFormat("yyyyMMddHHmmss"); //重命名(保單號+時間) localName = localPdfName; if(!"".equals(url) && url !=null){ // String backUrl = "ftp://172.18.100.165/Imagedownload/0180050037-個險合同-電子合同-201537071208(66e735db-8ddf-4e0e-b70c-339544ff630b).PDF"; fileName = url.split("/")[4]; pathUrl = url.split("/")[2]; //生產環境ftp判斷 if("172.16.252.100".equals(pathUrl)){ username = "shwasextp20\\ftp"; }else if("172.16.252.110".equals(pathUrl)){ username = "shwasextp21\\ftp"; }else{ username = "shwasextt20\\ftp"; } FTPClient ftp = new FTPClient(); try { ftp.connect(pathUrl,port); ftp.login(username,password); System.out.println(ftp.isConnected()); ftp.enterLocalPassiveMode(); ftp.setControlEncoding("GBK"); ftp.setFileType(ftp.BINARY_FILE_TYPE); ftp.changeWorkingDirectory(remotePath); OutputStream outputStream = null; FTPFile[] fs = ftp.listFiles(); for (int i = 0; i < fs.length; i++) { FTPFile ff = fs[i]; if (ff.getName().equals(fileName)) { InputStream in = ftp.retrieveFileStream(new String(ff.getName().getBytes("GBK"), "ISO-8859-1")); int len = 0; long size = 0; byte[] bt = new byte[1024]; outputStream=new BufferedOutputStream(new FileOutputStream(localPath+"\\"+localName+".pdf")); while ((len = in.read(bt)) > 0) { outputStream.write(bt, 0, len); // outputStream.flush(); size = size + len; // System.out.println(fileName + "已xiazai :" + size); } newUrl = "cms/wwwroot/ng/downLoad/"+localName+".pdf"; outputStream.flush(); } } outputStream.close(); ftp.logout(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return newUrl; }