详解JAVA中使用FTPClient工具类上传下载
程序员文章站
2023-12-20 16:28:34
详解java中使用ftpclient工具类上传下载
在java程序中,经常需要和ftp打交道,比如向ftp服务器上传文件、下载文件。本文简单介绍如何利用jakarta c...
详解java中使用ftpclient工具类上传下载
在java程序中,经常需要和ftp打交道,比如向ftp服务器上传文件、下载文件。本文简单介绍如何利用jakarta commons中的ftpclient(在commons-net包中)实现上传下载文件。
1、写一个javabean文件,描述ftp上传或下载的信息
实例代码:
public class ftpusebean { private string host; private integer port; private string username; private string password; private string ftpseperator; private string ftppath=""; private int repeattime = 0;//连接ftp服务器的次数 public string gethost() { return host; } public void sethost(string host) { this.host = host; } public integer getport() { return port; } public void setport(integer port) { this.port = port; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public void setftpseperator(string ftpseperator) { this.ftpseperator = ftpseperator; } public string getftpseperator() { return ftpseperator; } public void setftppath(string ftppath) { if(ftppath!=null) this.ftppath = ftppath; } public string getftppath() { return ftppath; } public void setrepeattime(int repeattime) { if (repeattime > 0) this.repeattime = repeattime; } public int getrepeattime() { return repeattime; } /** * take an example:<br> * ftp://username:password@ip:port/ftppath/ * @return */ public string getftpurl() { stringbuffer buf = new stringbuffer(); 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()); return buf.tostring(); } }
2、导入包commons-net-1.4.1.jar
package com.util; import java.io.bufferedreader; import java.io.bytearrayoutputstream; import java.io.dataoutputstream; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.net.socketexception; import java.net.url; import java.net.urlconnection; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import org.apache.commons.net.ftp.ftp; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpclientconfig; import org.apache.commons.net.ftp.ftpfile; import com.bean.ftpusebean; public class ftputil extends ftpclient { private static log log = logfactory.getlog(ftputil.class); private ftpusebean ftpusebean; //获取目标路径下的文件属性信息,主要是获取文件的size private ftpfile[] files; public ftpusebean getftpusebean() { return ftpusebean; } public ftputil(){ super(); } public void setftpusebean(ftpusebean ftpusebean) { this.ftpusebean = ftpusebean; } public boolean ftplogin() { boolean islogined = false; try { log.debug("ftp login start ..."); int repeattime = ftpusebean.getrepeattime(); for (int i = 0; i < repeattime; i++) { super.connect(ftpusebean.gethost(), ftpusebean.getport()); islogined = super.login(ftpusebean.getusername(), ftpusebean.getpassword()); if (islogined) break; } if(islogined) log.debug("ftp login successfully ..."); else log.debug("ftp login failed ..."); return islogined; } catch (socketexception e) { log.error("", e); return false; } catch (ioexception e) { log.error("", e); return false; } catch (runtimeexception e) { log.error("", e); return false; } } public void setftptoutf8() throws ioexception { ftpclientconfig conf = new ftpclientconfig(); super.configure(conf); super.setfiletype(ftp.image_file_type); int reply = super.sendcommand("opts utf8 on"); if (reply == 200) { // utf8 command super.setcontrolencoding("utf-8"); } } public void close() { if (super.isconnected()) { try { super.logout(); super.disconnect(); log.debug("ftp logout ...."); } catch (exception e) { log.error(e.getmessage()); throw new runtimeexception(e.tostring()); } } } public void uploadfiletoftpbyis(inputstream inputstream, string filename) throws ioexception { super.storefile(ftpusebean.getftppath()+filename, inputstream); } public file downftpfile(string filename, string localfilename) throws ioexception { file outfile = new file(localfilename); outputstream ostream = null; try { ostream = new fileoutputstream(outfile); super.retrievefile(ftpusebean.getftppath()+filename, ostream); return outfile; } finally { if (ostream != null) ostream.close(); } } public ftpfile[] listftpfiles() throws ioexception { return super.listfiles(ftpusebean.getftppath()); } public void deleteftpfiles(ftpfile[] ftpfiles) throws ioexception { string path = ftpusebean.getftppath(); for (ftpfile ff : ftpfiles) { if (ff.isfile()) { if (!super.deletefile(path + ff.getname())) throw new runtimeexception("delete file" + ff.getname() + " is n't seccess"); } } } public void deleteftpfile(string filename) throws ioexception { if (!super.deletefile(ftpusebean.getftppath() +filename)) throw new runtimeexception("delete file" + ftpusebean.getftppath() +filename + " is n't seccess"); } public inputstream downftpfile(string filename) throws ioexception { return super.retrievefilestream(ftpusebean.getftppath()+filename); } /** * * @return * @return stringbuffer * @description 下载ftp服务器上的文件,addr为带用户名和密码的url */ public stringbuffer downloadbufferbyurl(string addr) { bufferedreader in = null; try { url url = new url(addr); urlconnection conn = url.openconnection(); in = new bufferedreader(new inputstreamreader(conn.getinputstream())); string line; stringbuffer ret = new stringbuffer(); while ((line = in.readline()) != null) ret.append(line); return ret; } catch (exception e) { log.error(e); return null; } finally { try { if (null != in) in.close(); } catch (ioexception e) { e.printstacktrace(); log.error(e); } } } /** * * @return * @return byte[] * @description 下载ftp服务器上的文件,addr为带用户名和密码的url */ public byte[] downloadbytebyurl(string addr) { ftpclient ftp = null; try { url url = new url(addr); int port = url.getport()!=-1?url.getport():21; log.info("host:"+url.gethost()); log.info("port:"+port); log.info("userinfo:"+url.getuserinfo()); log.info("path:"+url.getpath()); ftp = new ftpclient(); ftp.setdatatimeout(30000); ftp.setdefaulttimeout(30000); ftp.setreaderthread(false); ftp.connect(url.gethost(), port); ftp.login(url.getuserinfo().split(":")[0], url.getuserinfo().split(":")[1]); ftpclientconfig conf = new ftpclientconfig("unix"); ftp.configure(conf); log.info(ftp.getreplystring()); ftp.enterlocalpassivemode(); //ftp.enterremotepassivemode() ftp.setfiletransfermode(ftp.stream_transfer_mode); int reply = ftp.sendcommand("opts utf8 on");// try to log.debug("alter to utf-8 encoding - reply:" + reply); if (reply == 200) { // utf8 command ftp.setcontrolencoding("utf-8"); } ftp.setfiletype(ftpclient.binary_file_type); log.info(ftp.getreplystring()); bytearrayoutputstream out=new bytearrayoutputstream(); dataoutputstream o=new dataoutputstream(out); string remotepath = url.getpath(); /** * fixed:if doen't remove the first "/" at the head of url, * the file can't be retrieved. */ if(remotepath.indexof("/")==0) { remotepath = url.getpath().replacefirst("/", ""); } ftp.retrievefile(remotepath, o); byte[] ret = out.tobytearray(); o.close(); string filepath = url.getpath(); ftp.changeworkingdirectory(filepath.substring(0,filepath.lastindexof("/"))); files = ftp.listfiles(); return ret; } catch (exception ex) { log.error("failed to download file from ["+addr+"]!"+ex); } finally { try { if (null!=ftp) ftp.disconnect(); } catch (exception e) { // } } return null; // stringbuffer buffer = downloadbufferbyurl(addr); // return null == buffer ? null : buffer.tostring().getbytes(); } public ftpfile[] getfiles() { return files; } public void setfiles(ftpfile[] files) { this.files = files; } // public static void getftpfilesize(string addr){ // // ftpclient ftp = null; // // try { // // url url = new url(addr); // // int port = url.getport()!=-1?url.getport():21; // log.info("host:"+url.gethost()); // log.info("port:"+port); // log.info("userinfo:"+url.getuserinfo()); // log.info("path:"+url.getpath()); // // ftp = new ftpclient(); // // ftp.setdatatimeout(30000); // ftp.setdefaulttimeout(30000); // ftp.setreaderthread(false); // ftp.connect(url.gethost(), port); // ftp.login(url.getuserinfo().split(":")[0], url.getuserinfo().split(":")[1]); // ftpclientconfig conf = new ftpclientconfig("unix"); // ftp.configure(conf); // log.info(ftp.getreplystring()); // // ftp.enterlocalpassivemode(); //ftp.enterremotepassivemode() // ftp.setfiletransfermode(ftp.stream_transfer_mode); // // int reply = ftp.sendcommand("opts utf8 on");// try to // // log.debug("alter to utf-8 encoding - reply:" + reply); // if (reply == 200) { // utf8 command // ftp.setcontrolencoding("utf-8"); // } // ftp.setfiletype(ftpclient.binary_file_type); // ftp.changeworkingdirectory(url.getpath()); // ftpfile[] files = ftp.listfiles(); // for (ftpfile flie : files){ // system.out.println(new string(flie.getname().getbytes("gbk"),"iso8859-1")); // system.out.println(flie.getsize()); // } // // // } catch (exception ex) { // log.error("failed to download file from ["+addr+"]!"+ex); // } finally { // try {<pre class="java" name="code"> if (null!=ftp) // ftp.disconnect(); // } catch (exception e) { } } } }
以上就是java ftpclient工具类的上传和下载的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!