javaftp上传下载

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" ) ) ; 
	}

你可能感兴趣的:(javaftp上传下载)