javaftp上传下载

2014-11-24 08:14:28 · 作者: · 浏览: 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
  
    ftpRecursive(FTPClient client,String dir, String localDir) throws Exception{
		List
   
     fileNames = new Vector
    
     ( ) ; 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" ) ) ; }