java编写ftp下载工具需要用到java写一个ftp的工具,因为只有一点点java基础,但是由于好几年不用,几乎算是不会了,只 好一点点来搞,还好能捡起来。不过因为是在Linux下使用javac编译,不是在WIN下使用IDE来做这些事情,所以 在运行和编译上又费了一些时间,不过正是因为这样对JAVA的一些编译、运行的知识又了解了一些。对于ftp下载工具,代码如下: 复制代码代码如下:importjava.io.File;importjava.io.FileInputStream;im portjava.io.FileNotFoundException;importjava.io.FileOutputStre am;importjava.io.IOException;importjava.io.InputStream;impor tjava.io.OutputStream;importjava.net.SocketException;importo rg.apache.commons.net.ftp.FTPClient;importorg.apache.commons.ne t.ftp.FTPReply;publicclassFtpClient{privateStringhost;priv ateintport;privateStringusername;privateStringpassword;p rivatebooleanbinaryTransfer=true;privatebooleanpassiveMode =true;privateStringencoding="UTF-8";privateintclientTim eout=3000;privatebooleanflag=true;privateFTPClientftpClien t=null;publicStringgetHost(){returnhost;}publicvoidset Host(Stringhost){this.host=host;}publicintgetPort(){re turnport;}publicvoidsetPort(intport){this.port=port;} publicStringgetUsername(){returnusername;}publicvoidsetU sername(Stringusername){this.username=username;}publicStr inggetPassword(){returnpassword;}publicvoidsetPassword(St ringpassword){this.password=password;}publicbooleanisBin aryTransfer(){returnbinaryTransfer;}publicvoidsetBinaryTra nsfer(booleanbinaryTransfer){this.binaryTransfer=binaryTrans fer;}publicbooleanisPassiveMode(){returnpassiveMode;}pub licvoidsetPassiveMode(booleanpassiveMode){this.passiveMode= passiveMode;}publicStringgetEncoding(){returnencoding;} publicvoidsetEncoding(Stringencoding){this.encoding=encodi ng;}publicintgetClientTimeout(){returnclientTimeout;}pub licvoidsetClientTimeout(intclientTimeout){this.clientTimeout =clientTimeout;}publicFtpClient(StringHost){this.username ="anonymous";this.encoding="utf-8";this.binaryTransfer=true; this.binaryTransfer=true;this.port=21;this.host=Host;try{t his.ftpClient=getFTPClient();}catch(Exceptione){System.out. println("CreateFTPClienterror!");}}privateFTPClientgetFTPClie nt()throwsIOException{FTPClientftpClient=newFTPClient(); ftpClient.setControlEncoding(encoding);connect(ftpClient);if(pas siveMode){ftpClient.enterLocalPassiveMode();}setFileType(ftpC lient);try{ftpClient.setSoTimeout(clientTimeout);}catch(Soc ketExceptione){thrownewIOException("Settimeouterror.",e); }returnftpClient;}privatevoidsetFileType(FTPClientftpClie nt)throwsIOException{try{if(binaryTransfer){ftpClient.se tFileType(FTPClient.BINARY_FILE_TYPE);}else{ftpClient.setFile Type(FTPClient.ASCII_FILE_TYPE);}}catch(IOExceptione){thro wnewIOException("Couldnottosetfiletype.",e);}}publicb ooleanconnect(FTPClientftpClient)throwsIOException{try{ft pClient.connect(host,port);intreply=ftpClient.getReplyCode() ;if(FTPReply.isPositiveCompletion(reply)){if(ftpClient.login (username,password)){setFileType(ftpClient);returntrue;}} else{this.ftpClient.disconnect();thrownewIOException("FTPse rverrefusedconnection.");}}catch(IOExceptione){if(this. ftpClient.isConnected()){try{this.ftpClient.disconnect();}ca tch(IOExceptione1){thrownewIOException("Couldnotdisconnec tfromserver.",e);}}thrownewIOException("Couldnotconnect toserver.",e);}returnfalse;}privatevoiddisconnect()thr owsIOException{try{this.ftpClient.logout();}catch(IOExcep tione){System.out.println("logoutmaytimeout!");}finally{if (this.ftpClient.isConnected()){this.ftpClient.disconnect();} }}publicInputStreamgetStream(StringserverFile)throwsIOExce ption{InputStreaminStream=null;try{inStream=this.ftpClient .retrieveFileStream(serverFile);System.out.println("inStreamget over!");returninStream;}catch(IOExceptione){System.out.print ln("getstreamexception");returnnull;}}publicbooleanwriteStre am(InputStreaminput,StringlocalFile)throwsIOException{FileO utputStreamfout=newFileOutputStream(localFile);intch=0;if( input==null){System.out.println("inputisnull");returnfalse;} try{ch=input.read();while(ch!=-1){fout.write(ch);ch=input. read();}System.out.println("writeover!");returnflag;}catch(IO Exceptione){thrownewIOException("Couldn''tgetfilefromserve r.",e);}}publicbooleanisExist(StringremoteFilePath)throwsIO Exception{try{Filefile=newFile(remoteFilePath);StringremotePat h=remoteFilePath.substring(0,(remoteFilePath.indexOf(file.getName ())-1));String[]listNames=this.ftpClient.listNames(remotePath) ;System.out.println(remoteFilePath);for(inti=0;ith;i++){System.out.println(listNames[i]);if(remoteFilePath.equals (listNames[i])){flag=true;System.out.println("file:"+file.getName ()+"existed");break;}else{flag=false;}}}catch(IOExceptione) {thrownewIOException("FILEEXCEPTION",e);}returnflag;}//ma infortestingpublicstaticvoidmain(String[]args)throwsIOExc eption{Stringhostname="cp01-testing-ps7130.cp01.baidu.com";S tringserverFile="/home/work/check_disk.sh";StringlocalFile="/ho me/work/workspace/project/dhc2-0/dhc/base/ftp/task_get";FtpClient ftp=newFtpClient(hostname);System.out.println(ftp://ftp.isEx ist(serverFileftp.isExist(serverFile));ftp://ftp.writeStream(ftp. getStream(serverFileftp.writeStream(ftp.getStream(serverFile),lo calFile);ftp://ftp.disconnectftp.disconnect();}}这个工具是为了配合另外一个Ha doop工具做集群上传用的,所以里面的把input和output流分开了,也是为了方便另外一个工具使用。补充一点,如何 在linux配置运行:如果这样的代码需要在linux下环境运行,首先要配置好响应的包,例如复制代码代码如下:importorg.apache.commons.net.ftp.FTPClient;这个包在apache的网站上直接下载就行,解压后找到对应的jar包,在编译的时候进行引用:复制代码代码如下:exportFTPPATH="${路径}/xxx.jar"javac-classpath$CLASSPATH:$FTPPATHFtpClient.java同样,在运行的时候也要指定classpath:复制代码代码如下:java-classpath$CLASSPATH:$FTPPATHFtpClient建议不要把$FTPPATH包含在CLASSPATH中,用什么包就引用什么环境变量就行了,没必要一股脑都添加进去,就像我们没必要import所有的包一样。 |
|