java使用Apache工具集實(shí)現(xiàn)ftp文件傳輸代碼詳解
本文主要介紹如何使用Apache工具集commons-net提供的ftp工具實(shí)現(xiàn)向ftp服務(wù)器上傳和下載文件。
一、準(zhǔn)備
需要引用commons-net-3.5.jar包。
使用maven導(dǎo)入:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </dependency>
手動(dòng)下載:
http://www.dbjr.com.cn/softs/550085.html
二、連接FTP Server
/** * 連接FTP Server * @throws IOException */ public static final String ANONYMOUS_USER="anonymous"; private FTPClient connect(){ FTPClient client = new FTPClient(); try{ //連接FTP Server client.connect(this.host, this.port); //登陸 if(this.user==null||"".equals(this.user)){ //使用匿名登陸 client.login(ANONYMOUS_USER, ANONYMOUS_USER); } else{ client.login(this.user, this.password); } //設(shè)置文件格式 client.setFileType(FTPClient.BINARY_FILE_TYPE); //獲取FTP Server 應(yīng)答 int reply = client.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ client.disconnect(); return null; } //切換工作目錄 changeWorkingDirectory(client); System.out.println("===連接到FTP:"+host+":"+port); } catch(IOException e){ return null; } return client; } /** * 切換工作目錄,遠(yuǎn)程目錄不存在時(shí),創(chuàng)建目錄 * @param client * @throws IOException */ private void changeWorkingDirectory(FTPClient client) throws IOException{ if(this.ftpPath!=null&&!"".equals(this.ftpPath)){ Boolean ok = client.changeWorkingDirectory(this.ftpPath); if(!ok){ //ftpPath 不存在,手動(dòng)創(chuàng)建目錄 StringTokenizer token = new StringTokenizer(this.ftpPath,"\\//"); while(token.hasMoreTokens()){ String path = token.nextToken(); client.makeDirectory(path); client.changeWorkingDirectory(path); } } } } /** * 斷開FTP連接 * @param ftpClient * @throws IOException */ public void close(FTPClient ftpClient) throws IOException{ if(ftpClient!=null && ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); } System.out.println("!!!斷開FTP連接:"+host+":"+port); }
host:ftp服務(wù)器ip地址
port:ftp服務(wù)器端口
user:登陸用戶
password:登陸密碼
登陸用戶為空時(shí),使用匿名用戶登陸。
ftpPath:ftp路徑,ftp路徑不存在時(shí)自動(dòng)創(chuàng)建,如果是多層目錄結(jié)構(gòu),需要迭代創(chuàng)建目錄。
三、上傳文件
/** * 上傳文件 * @param targetName 上傳到ftp文件名 * @param localFile 本地文件路徑 * @return */ public Boolean upload(String targetName,String localFile){ //連接ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("連接FTP服務(wù)器["+host+":"+port+"]失?。?); return false; } File file = new File(localFile); //設(shè)置上傳后文件名 if(targetName==null||"".equals(targetName)) targetName = file.getName(); FileInputStream fis = null; try{ long now = System.currentTimeMillis(); //開始上傳文件 fis = new FileInputStream(file); System.out.println(">>>開始上傳文件:"+file.getName()); Boolean ok = ftpClient.storeFile(targetName, fis); if(ok){ //上傳成功 long times = System.currentTimeMillis() - now; System.out.println(String.format(">>>上傳成功:大?。?s,上傳時(shí)間:%d秒", formatSize(file.length()),times/1000)); } else//上傳失敗 System.out.println(String.format(">>>上傳失敗:大?。?s", formatSize(file.length()))); } catch(IOException e){ System.err.println(String.format(">>>上傳失?。捍笮。?s", formatSize(file.length()))); e.printStackTrace(); return false; } finally{ try{ if(fis!=null) fis.close(); close(ftpClient); } catch(Exception e){ } } return true; }
四、下載文件
/** * 下載文件 * @param localPath 本地存放路徑 * @return */ public int download(String localPath){ // 連接ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("連接FTP服務(wù)器["+host+":"+port+"]失敗!"); return 0; } File dir = new File(localPath); if(!dir.exists()) dir.mkdirs(); FTPFile[] ftpFiles = null; try{ ftpFiles = ftpClient.listFiles(); if(ftpFiles==null||ftpFiles.length==0) return 0; } catch(IOException e){ return 0; } int c = 0; for (int i=0;i<ftpFiles.length;i++){ FileOutputStream fos = null; try{ String name = ftpFiles[i].getName(); fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name)); System.out.println("<<<開始下載文件:"+name); long now = System.currentTimeMillis(); Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos); if(ok){ //下載成功 long times = System.currentTimeMillis() - now; System.out.println(String.format("<<<下載成功:大?。?s,上傳時(shí)間:%d秒", formatSize(ftpFiles[i].getSize()),times/1000)); c++; } else{ System.out.println("<<<下載失敗"); } } catch(IOException e){ System.err.println("<<<下載失敗"); e.printStackTrace(); } finally{ try{ if(fos!=null) fos.close(); close(ftpClient); } catch(Exception e){ } } } return c; }
格式化文件大小
private static final DecimalFormat DF = new DecimalFormat("#.##"); /** * 格式化文件大?。˙,KB,MB,GB) * @param size * @return */ private String formatSize(long size){ if(size<1024){ return size + " B"; }else if(size<1024*1024){ return size/1024 + " KB"; }else if(size<1024*1024*1024){ return (size/(1024*1024)) + " MB"; }else{ double gb = size/(1024*1024*1024); return DF.format(gb)+" GB"; } }
五、測(cè)試
public static void main(String args[]){ FTPTest ftp = new FTPTest("192.168.1.10",21,null,null,"/temp/2016/12"); ftp.upload("newFile.rar", "D:/ftp/TeamViewerPortable.rar"); System.out.println(""); ftp.download("D:/ftp/"); }
結(jié)果
===連接到FTP:192.168.1.10:21 >>>開始上傳文件:TeamViewerPortable.rar >>>上傳成功:大小:5 MB,上傳時(shí)間:3秒 !!!斷開FTP連接:192.168.1.10:21 ===連接到FTP:192.168.1.10:21 <<<開始下載文件:newFile.rar <<<下載成功:大?。? MB,上傳時(shí)間:4秒 !!!斷開FTP連接:192.168.1.10:21
總結(jié)
以上就是本文關(guān)于java使用Apache工具集實(shí)現(xiàn)ftp文件傳輸代碼詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
Mybatis-Plus實(shí)體類繼承Model的使用小結(jié)
Mybatis-Plus實(shí)體類繼承Model的使用是Mybatis-Plus中的一個(gè)重要特性,它允許開發(fā)者通過繼承Model類來快速實(shí)現(xiàn)一些通用的功能,本文主要介紹了Mybatis-Plus實(shí)體類繼承Model的使用小結(jié),感興趣的可以了解一下2024-07-07Java8中 LocalDate和java.sql.Date的相互轉(zhuǎn)換操作
這篇文章主要介紹了Java8中 LocalDate和java.sql.Date的相互轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12java面試LruCache?和?LinkedHashMap及算法實(shí)現(xiàn)
這篇文章主要為大家介紹了java面試LruCache?和?LinkedHashMap及算法實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02通過實(shí)例了解cookie機(jī)制特性及使用方法
這篇文章主要介紹了通過實(shí)例了解cookie機(jī)制特性及使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Java使用POI解析帶圖片的excel文件(簡(jiǎn)潔好用!)
這篇文章主要給大家介紹了關(guān)于Java如何使用POI解析帶圖片的excel文件的相關(guān)資料,最近項(xiàng)目需要讀取excel中的信息,帶圖片,所以這里給大家總結(jié)下,需要的朋友可以參考下2023-08-08Spring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法
最近做項(xiàng)目遇到這樣的應(yīng)用場(chǎng)景,項(xiàng)目需要同時(shí)連接兩個(gè)不同的數(shù)據(jù)庫A, B,并且它們都為主從架構(gòu),一臺(tái)寫庫,多臺(tái)讀庫。下面小編給大家?guī)砹薙pring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法,需要的朋友參考下吧2018-01-01