JAVA+FTP實現跨伺服器獲取檔案,支援區域網和外網
阿新 • • 發佈:2019-01-05
1.FTP服務是filezilla server。
下載地址:
https://filezilla-project.org/
2.filezilla server安裝及配置教程
教程地址:
https://jingyan.baidu.com/article/17bd8e521067fe85ab2bb8ee.html
3.依賴jar包:commons-net-3.1,httpclient-4.3.5,httpcore-4.4.5
下載地址:
http://download.csdn.net/download/zhong_jay/10180699
4.程式碼如下:
/** * * @Title: ftpDownload * @Description: ftp跨伺服器檔案獲取 * @author jay * @date 2017年12月29日 下午7:05:13 * @return boolean * * @param ftpUrl ftp服務地址 * @param userName //登入名 * @param pass //密碼 * @param port //埠號,預設21 * @param directory //FTP伺服器上的相對路徑 ,\\代表根目錄 * @param fileName //要獲取的檔名 * @param localPath //獲取後儲存到本地的路徑 * @return * @throws IOException */ public static boolean ftpDownload(String ftpUrl,String userName,String pass,int port,String directory, String fileName,String localPath) throws IOException{ FTPClient ftpClient = new FTPClient(); int reply; try { ftpClient.connect(ftpUrl,port); ftpClient.login(userName, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setBufferSize(1024); // 設定檔案型別(二進位制) ftpClient.changeWorkingDirectory(directory); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //設定連線超時和資料傳輸超時,對於效能有要求的專案,設定這兩個屬性很重要。例如,設定為60秒: ftpClient.setDataTimeout(60000); //設定傳輸超時時間為60秒 ftpClient.setConnectTimeout(60000); //連線超時為60秒 reply = ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { //reply狀態標識碼,200<=reply<300登入成功 ftpClient.disconnect(); System.err.println("FTP服務連線失敗,請檢查相關引數是否正確!"); System.exit(1); return false; } //獲取FTP對應路徑下的檔案集合 FTPFile[] fs = ftpClient.listFiles(); for(FTPFile ff:fs){ //下載當前目錄下所有檔案 if(ff.getName().equals(fileName)){ String path=localPath+"\\"+ff.getName(); File localFile = new File(path); OutputStream is = new FileOutputStream(localFile); ftpClient.retrieveFile(ff.getName(), is); is.close(); } } System.out.println("FTP檔案下載成功!"); return true; } catch(NumberFormatException e){ throw e; } catch(FileNotFoundException e){ throw new FileNotFoundException(); } catch (IOException e) { throw new IOException(e); } finally { if(ftpClient.isConnected()){ try { ftpClient.disconnect(); } catch (IOException e) { throw new RuntimeException("關閉FTP連線發生異常!", e); } } } }