关闭

javaftp上传下载

1077人阅读 评论(0) 收藏 举报
分类:
public static FTPClient getFtpClient(String address, int port,
			String uname, String pwd , String encoding) throws Exception {
		FTPClient client = null;

		client = new FTPClient();
		client.connect(address, port);
		boolean islogin = client.login(uname, pwd);
		if (!islogin) {
			throw new Exception("帐号或者密码错误");
		}
		client.setControlEncoding( encoding);
		
		return client; 
	}
	
	/**
	 * FTP文件递归 
	 * @throws Exception 
	 * */
	public static List<String> ftpRecursive(FTPClient client,String dir, String localDir) throws Exception{
		List<String> fileNames = new Vector<String>( ) ; 
		FTPFile[]ftpFiles=client.listFiles( dir ) ;
		for(FTPFile file : ftpFiles){
			String name = dir + "/" + file.getName() ;  
			if(file.isDirectory()){
				ftpRecursive(client, dir, name ) ; 
			}else{
				File localFile = new File( localDir + name); 
				if(!localFile.exists()){
					downFile(client, name , localFile) ;   
				}
			}
		}
		return fileNames ; 
	}
	
	public static void downFile(FTPClient client , String fileName,File localFile){
		try {
			System.out.println( "正在下载文件:" +  fileName ); 
			localFile.getParentFile().mkdirs() ;
			InputStream is = client.retrieveFileStream( fileName ) ; 
			if(is == null){
				System.out.println( "下载失败" + fileName ); 
				return ;
			}
			OutputStream os = new FileOutputStream( localFile );  
			int len = -1 ; 
			byte[]buffer = new byte[1024]; 
			int all = 0 ; 
			while( (len = is.read(buffer)) != -1 ){
				all += len ;
				System.out.println( "下载:" + all ); 
				os.write(buffer, 0 , len ) ; 
			}
			os.flush() ;
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}
	/**javaftp上传*/
	public static boolean upload(FTPClient client,String localFile,String remoteName){
		try {
			File file = new File( localFile ); 
			if(file.exists()){
				InputStream local = new FileInputStream(file);
				
				return client.appendFile(remoteName, local) ; 
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	public static void main(String[] args)throws Exception {
		FTPClient client =  FTP.getFtpClient( "a.iding.me", 21, "aaa", "aaavvv" , "UTF-8" ) ;  
		
		//System.out.println( FTP.ftpRecursive( client , dir , localDir).size() );  
		System.out.println( FTP.upload(client , 
				"E:/soft/down/记事本.txt" , "/记事本.txt" ) ) ; 
	}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:579775次
    • 积分:6344
    • 等级:
    • 排名:第4077名
    • 原创:187篇
    • 转载:14篇
    • 译文:0篇
    • 评论:126条
    最新评论