详解JAVA中使用FTPClient工具类上传下载
详解JAVA中使用FTPClient工具类上传下载
在Java程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件。本文简单介绍如何利用jakartacommons中的FTPClient(在commons-net包中)实现上传下载文件。
1、写一个javabean文件,描述ftp上传或下载的信息
实例代码:
publicclassFtpUseBean{ privateStringhost; privateIntegerport; privateStringuserName; privateStringpassword; privateStringftpSeperator; privateStringftpPath=""; privateintrepeatTime=0;//连接ftp服务器的次数 publicStringgetHost(){ returnhost; } publicvoidsetHost(Stringhost){ this.host=host; } publicIntegergetPort(){ returnport; } publicvoidsetPort(Integerport){ this.port=port; } publicStringgetUserName(){ returnuserName; } publicvoidsetUserName(StringuserName){ this.userName=userName; } publicStringgetPassword(){ returnpassword; } publicvoidsetPassword(Stringpassword){ this.password=password; } publicvoidsetFtpSeperator(StringftpSeperator){ this.ftpSeperator=ftpSeperator; } publicStringgetFtpSeperator(){ returnftpSeperator; } publicvoidsetFtpPath(StringftpPath){ if(ftpPath!=null) this.ftpPath=ftpPath; } publicStringgetFtpPath(){ returnftpPath; } publicvoidsetRepeatTime(intrepeatTime){ if(repeatTime>0) this.repeatTime=repeatTime; } publicintgetRepeatTime(){ returnrepeatTime; } /** *takeanexample:
*ftp://userName:password@ip:port/ftpPath/ *@return */ publicStringgetFTPURL(){ StringBufferbuf=newStringBuffer(); buf.append("ftp://"); buf.append(getUserName()); buf.append(":"); buf.append(getPassword()); buf.append("@"); buf.append(getHost()); buf.append(":"); buf.append(getPort()); buf.append("/"); buf.append(getFtpPath()); returnbuf.toString(); } }
2、导入包commons-net-1.4.1.jar
packagecom.util; importjava.io.BufferedReader; importjava.io.ByteArrayOutputStream; importjava.io.DataOutputStream; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.net.SocketException; importjava.net.URL; importjava.net.URLConnection; importorg.apache.commons.logging.Log; importorg.apache.commons.logging.LogFactory; importorg.apache.commons.net.ftp.FTP; importorg.apache.commons.net.ftp.FTPClient; importorg.apache.commons.net.ftp.FTPClientConfig; importorg.apache.commons.net.ftp.FTPFile; importcom.bean.FtpUseBean; publicclassFtpUtilextendsFTPClient{ privatestaticLoglog=LogFactory.getLog(FtpUtil.class); privateFtpUseBeanftpUseBean; //获取目标路径下的文件属性信息,主要是获取文件的size privateFTPFile[]files; publicFtpUseBeangetFtpUseBean(){ returnftpUseBean; } publicFtpUtil(){ super(); } publicvoidsetFtpUseBean(FtpUseBeanftpUseBean){ this.ftpUseBean=ftpUseBean; } publicbooleanftpLogin(){ booleanisLogined=false; try{ log.debug("ftploginstart..."); intrepeatTime=ftpUseBean.getRepeatTime(); for(inti=0;iif(null!=ftp) //ftp.disconnect(); //}catch(Exceptione){ } } } }
以上就是JAVAFTPClient工具类的上传和下载的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!