国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

java使用Apache工具集實現ftp文件傳輸代碼詳解

2024-07-13 10:15:10
字體:
來源:轉載
供稿:網友

本文主要介紹如何使用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>

 

二、連接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);		}		//設置文件格式		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 server	FTPClient 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 server	FTPClient 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文件傳輸代碼詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平定县| 苏州市| 汶上县| 荃湾区| 庆云县| 阿拉善右旗| 小金县| 绩溪县| 焦作市| 卢氏县| 安阳市| 吉首市| 布尔津县| 法库县| 宝山区| 东至县| 龙井市| 玉山县| 霞浦县| 枣强县| 库伦旗| 吉木萨尔县| 秭归县| 乌兰县| 名山县| 阿拉善右旗| 黎平县| 昔阳县| 新巴尔虎右旗| 临潭县| 威宁| 金阳县| 雷山县| 桂林市| 宝丰县| 大兴区| 乐平市| 平武县| 定日县| 灌云县| 佛冈县|