本文主要介紹如何使用Apache工具集commons-net提供的ftp工具實現向ftp服務器上傳和下載文件。
一、準備
需要引用commons-net-3.5.jar包。
使用maven導入:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version></dependency>
手動下載:
//www.VeVB.COm/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 Serverclient.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);}//設置文件格式client.setFileType(FTPClient.BINARY_FILE_TYPE);//獲取FTP Server 應答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;}/** * 切換工作目錄,遠程目錄不存在時,創建目錄* @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 不存在,手動創建目錄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服務器ip地址
port:ftp服務器端口
user:登陸用戶
password:登陸密碼登陸用戶為空時,使用匿名用戶登陸。
ftpPath:ftp路徑,ftp路徑不存在時自動創建,如果是多層目錄結構,需要迭代創建目錄。
三、上傳文件
/** * 上傳文件* @param targetName 上傳到ftp文件名* @param localFile 本地文件路徑* @return */public Boolean upload(String targetName,String localFile){//連接ftp serverFTPClient ftpClient = connect();if(ftpClient==null){System.out.println("連接FTP服務器["+host+":"+port+"]失敗!");return false;}File file = new File(localFile);//設置上傳後文件名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,上傳時間:%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 serverFTPClient ftpClient = connect();if(ftpClient==null){System.out.println("連接FTP服務器["+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,上傳時間:%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("#.##"); /** * 格式化文件大小(B,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"; } }五、測試
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/"); }結果
===連接到FTP:192.168.1.10:21>>>開始上傳文件:TeamViewerPortable.rar>>>上傳成功:大小:5 MB,上傳時間:3秒!!!斷開FTP連接:192.168.1.10:21===連接到FTP:192.168.1.10:21<<<開始下載文件:newFile.rar<<<下載成功:大小:5 MB,上傳時間:4秒!!!斷開FTP連接:192.168.1.10:21
總結
以上就是本文關於java使用Apache工具集實現ftp文件傳輸代碼詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!