JAVA中使用FTPClient工具类上传下载

在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件。本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。

1、写一个javabean文件,描述ftp上传或下载的信息

  1. public class FtpUseBean {
  2. private String host;
  3. private Integer port;
  4. private String userName;
  5. private String password;
  6. private String ftpSeperator;
  7. private String ftpPath="";
  8. private int repeatTime = 0;//连接ftp服务器的次数
  9. public String getHost() {
  10. return host;
  11. }
  12. public void setHost(String host) {
  13. this.host = host;
  14. }
  15. public Integer getPort() {
  16. return port;
  17. }
  18. public void setPort(Integer port) {
  19. this.port = port;
  20. }
  21. public String getUserName() {
  22. return userName;
  23. }
  24. public void setUserName(String userName) {
  25. this.userName = userName;
  26. }
  27. public String getPassword() {
  28. return password;
  29. }
  30. public void setPassword(String password) {
  31. this.password = password;
  32. }
  33. public void setFtpSeperator(String ftpSeperator) {
  34. this.ftpSeperator = ftpSeperator;
  35. }
  36. public String getFtpSeperator() {
  37. return ftpSeperator;
  38. }
  39. public void setFtpPath(String ftpPath) {
  40. if(ftpPath!=null)
  41. this.ftpPath = ftpPath;
  42. }
  43. public String getFtpPath() {
  44. return ftpPath;
  45. }
  46. public void setRepeatTime(int repeatTime) {
  47. if (repeatTime > 0)
  48. this.repeatTime = repeatTime;
  49. }
  50. public int getRepeatTime() {
  51. return repeatTime;
  52. }
  53. /**
  54. * take an example:<br>
  55. * ftp://userName:password@ip:port/ftpPath/
  56. * @return
  57. */
  58. public String getFTPURL() {
  59. StringBuffer buf = new StringBuffer();
  60. buf.append("ftp://");
  61. buf.append(getUserName());
  62. buf.append(":");
  63. buf.append(getPassword());
  64. buf.append("@");
  65. buf.append(getHost());
  66. buf.append(":");
  67. buf.append(getPort());
  68. buf.append("/");
  69. buf.append(getFtpPath());
  70. return buf.toString();
  71. }
  72. }
  73. 2、导入包commons-net-1.4.1.jar
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
  1. package com.util;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStream;
  11. import java.net.SocketException;
  12. import java.net.URL;
  13. import java.net.URLConnection;
  14. import org.apache.commons.logging.Log;
  15. import org.apache.commons.logging.LogFactory;
  16. import org.apache.commons.net.ftp.FTP;
  17. import org.apache.commons.net.ftp.FTPClient;
  18. import org.apache.commons.net.ftp.FTPClientConfig;
  19. import org.apache.commons.net.ftp.FTPFile;
  20. import com.bean.FtpUseBean;
  21. public class FtpUtil extends FTPClient {
  22. private static Log log = LogFactory.getLog(FtpUtil.class);
  23. private FtpUseBean ftpUseBean;
  24. //获取目标路径下的文件属性信息,主要是获取文件的size
  25. private FTPFile[] files;
  26. public FtpUseBean getFtpUseBean() {
  27. return ftpUseBean;
  28. }
  29. public FtpUtil(){
  30. super();
  31. }
  32. public void setFtpUseBean(FtpUseBean ftpUseBean) {
  33. this.ftpUseBean = ftpUseBean;
  34. }
  35. public boolean ftpLogin() {
  36. boolean isLogined = false;
  37. try {
  38. log.debug("ftp login start ...");
  39. int repeatTime = ftpUseBean.getRepeatTime();
  40. for (int i = 0; i < repeatTime; i++) {
  41. super.connect(ftpUseBean.getHost(), ftpUseBean.getPort());
  42. isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword());
  43. if (isLogined)
  44. break;
  45. }
  46. if(isLogined)
  47. log.debug("ftp login successfully ...");
  48. else
  49. log.debug("ftp login failed ...");
  50. return isLogined;
  51. } catch (SocketException e) {
  52. log.error("", e);
  53. return false;
  54. } catch (IOException e) {
  55. log.error("", e);
  56. return false;
  57. } catch (RuntimeException e) {
  58. log.error("", e);
  59. return false;
  60. }
  61. }
  62. public void setFtpToUtf8() throws IOException {
  63. FTPClientConfig conf = new FTPClientConfig();
  64. super.configure(conf);
  65. super.setFileType(FTP.IMAGE_FILE_TYPE);
  66. int reply = super.sendCommand("OPTS UTF8 ON");
  67. if (reply == 200) { // UTF8 Command
  68. super.setControlEncoding("UTF-8");
  69. }
  70. }
  71. public void close() {
  72. if (super.isConnected()) {
  73. try {
  74. super.logout();
  75. super.disconnect();
  76. log.debug("ftp logout ....");
  77. } catch (Exception e) {
  78. log.error(e.getMessage());
  79. throw new RuntimeException(e.toString());
  80. }
  81. }
  82. }
  83. public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException {
  84. super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream);
  85. }
  86. public File downFtpFile(String fileName, String localFileName) throws IOException {
  87. File outfile = new File(localFileName);
  88. OutputStream oStream = null;
  89. try {
  90. oStream = new FileOutputStream(outfile);
  91. super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream);
  92. return outfile;
  93. } finally {
  94. if (oStream != null)
  95. oStream.close();
  96. }
  97. }
  98. public FTPFile[] listFtpFiles() throws IOException {
  99. return super.listFiles(ftpUseBean.getFtpPath());
  100. }
  101. public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException {
  102. String path = ftpUseBean.getFtpPath();
  103. for (FTPFile ff : ftpFiles) {
  104. if (ff.isFile()) {
  105. if (!super.deleteFile(path + ff.getName()))
  106. throw new RuntimeException("delete File" + ff.getName() + " is n't seccess");
  107. }
  108. }
  109. }
  110. public void deleteFtpFile(String fileName) throws IOException {
  111. if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName))
  112. throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess");
  113. }
  114. public InputStream downFtpFile(String fileName) throws IOException {
  115. return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName);
  116. }
  117. /**
  118. *
  119. * @return
  120. * @return StringBuffer
  121. * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL
  122. */
  123. public StringBuffer downloadBufferByURL(String addr) {
  124. BufferedReader in = null;
  125. try {
  126. URL url = new URL(addr);
  127. URLConnection conn = url.openConnection();
  128. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  129. String line;
  130. StringBuffer ret = new StringBuffer();
  131. while ((line = in.readLine()) != null)
  132. ret.append(line);
  133. return ret;
  134. } catch (Exception e) {
  135. log.error(e);
  136. return null;
  137. } finally {
  138. try {
  139. if (null != in)
  140. in.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. log.error(e);
  144. }
  145. }
  146. }
  147. /**
  148. *
  149. * @return
  150. * @return byte[]
  151. * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL
  152. */
  153. public byte[] downloadByteByURL(String addr) {
  154. FTPClient ftp = null;
  155. try {
  156. URL url = new URL(addr);
  157. int port = url.getPort()!=-1?url.getPort():21;
  158. log.info("HOST:"+url.getHost());
  159. log.info("Port:"+port);
  160. log.info("USERINFO:"+url.getUserInfo());
  161. log.info("PATH:"+url.getPath());
  162. ftp = new FTPClient();
  163. ftp.setDataTimeout(30000);
  164. ftp.setDefaultTimeout(30000);
  165. ftp.setReaderThread(false);
  166. ftp.connect(url.getHost(), port);
  167. ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
  168. FTPClientConfig conf = new FTPClientConfig("UNIX");
  169. ftp.configure(conf);
  170. log.info(ftp.getReplyString());
  171. ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()
  172. ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
  173. int reply = ftp.sendCommand("OPTS UTF8 ON");// try to
  174. log.debug("alter to utf-8 encoding - reply:" + reply);
  175. if (reply == 200) { // UTF8 Command
  176. ftp.setControlEncoding("UTF-8");
  177. }
  178. ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
  179. log.info(ftp.getReplyString());
  180. ByteArrayOutputStream out=new ByteArrayOutputStream();
  181. DataOutputStream o=new DataOutputStream(out);
  182. String remotePath = url.getPath();
  183. /**
  184. * Fixed:if doen't remove the first "/" at the head of url,
  185. * the file can't be retrieved.
  186. */
  187. if(remotePath.indexOf("/")==0) {
  188. remotePath = url.getPath().replaceFirst("/", "");
  189. }
  190. ftp.retrieveFile(remotePath, o);
  191. byte[] ret = out.toByteArray();
  192. o.close();
  193. String filepath = url.getPath();
  194. ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/")));
  195. files = ftp.listFiles();
  196. return ret;
  197. } catch (Exception ex) {
  198. log.error("Failed to download file from ["+addr+"]!"+ex);
  199. } finally {
  200. try {
  201. if (null!=ftp)
  202. ftp.disconnect();
  203. } catch (Exception e) {
  204. //
  205. }
  206. }
  207. return null;
  208. // StringBuffer buffer = downloadBufferByURL(addr);
  209. // return null == buffer ? null : buffer.toString().getBytes();
  210. }
  211. public FTPFile[] getFiles() {
  212. return files;
  213. }
  214. public void setFiles(FTPFile[] files) {
  215. this.files = files;
  216. }
  217. // public static void getftpfilesize(String addr){
  218. //
  219. // FTPClient ftp = null;
  220. //
  221. // try {
  222. //
  223. // URL url = new URL(addr);
  224. //
  225. // int port = url.getPort()!=-1?url.getPort():21;
  226. // log.info("HOST:"+url.getHost());
  227. // log.info("Port:"+port);
  228. // log.info("USERINFO:"+url.getUserInfo());
  229. // log.info("PATH:"+url.getPath());
  230. //
  231. // ftp = new FTPClient();
  232. //
  233. // ftp.setDataTimeout(30000);
  234. // ftp.setDefaultTimeout(30000);
  235. // ftp.setReaderThread(false);
  236. // ftp.connect(url.getHost(), port);
  237. // ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
  238. // FTPClientConfig conf = new FTPClientConfig("UNIX");
  239. // ftp.configure(conf);
  240. // log.info(ftp.getReplyString());
  241. //
  242. // ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()
  243. // ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
  244. //
  245. // int reply = ftp.sendCommand("OPTS UTF8 ON");// try to
  246. //
  247. // log.debug("alter to utf-8 encoding - reply:" + reply);
  248. // if (reply == 200) { // UTF8 Command
  249. // ftp.setControlEncoding("UTF-8");
  250. // }
  251. // ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
  252. // ftp.changeWorkingDirectory(url.getPath());
  253. // FTPFile[] files = ftp.listFiles();
  254. // for (FTPFile flie : files){
  255. // System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1"));
  256. // System.out.println(flie.getSize());
  257. // }
  258. //
  259. //
  260. // } catch (Exception ex) {
  261. // log.error("Failed to download file from ["+addr+"]!"+ex);
  262. // } finally {
  263. // try {<PRE class=java name="code"> if (null!=ftp)
  264. // ftp.disconnect();
  265. // } catch (Exception e) {
  266. }
  267. }
  268. }
  269. }</PRE>
  270. <PRE></PRE>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值