关键词搜索

源码搜索 ×
×

Apache FTP文件上传、下载、修改文件名、删除

发布2014-04-24浏览14258次

详情内容

 前言:Apache FTP 是应用比较广泛的FTP上传客户端工具,它易于操作,代码简略,结构清晰,是做FTP文件客户端管理软件的优先之选。FTP的操作包括:FTP文件上传(断点续传)、FTP文件下载、FTP文件重命名、FTP文件删除,这些操作已经将FTP应用管理的方式发挥的淋漓尽致了,So 我一直都用此种方式来实现FTP文件服务器的管理工作;下附FTP工具代码。

1、FTP文件操作状态枚举类

  1. package com.scengine.wtms.utils.ftp;
  2. public enum FTPStatus
  3. {
  4. File_Exits(0), Create_Directory_Success(1), Create_Directory_Fail(2), Upload_From_Break_Success(3), Upload_From_Break_Faild(4), Download_From_Break_Success(5), Download_From_Break_Faild(6), Upload_New_File_Success(7), Upload_New_File_Failed(8), Delete_Remote_Success(9), Delete_Remote_Faild(10),Remote_Bigger_Local(11),Remote_smaller_local(12),Not_Exist_File(13),Remote_Rename_Success(14),Remote_Rename_Faild(15),File_Not_Unique(16);
  5. private int status;
  6. public int getStatus()
  7. {
  8. return status;
  9. }
  10. public void setStatus(int status)
  11. {
  12. this.status = status;
  13. }
  14. FTPStatus(int status)
  15. {
  16. this.status = status;
  17. }
  18. }

2、FTP文件操作工具代码

  1. package com.scengine.wtms.utils.ftp;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.PrintWriter;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.apache.commons.net.PrintCommandListener;
  11. import org.apache.commons.net.ftp.FTP;
  12. import org.apache.commons.net.ftp.FTPClient;
  13. import org.apache.commons.net.ftp.FTPFile;
  14. import org.apache.commons.net.ftp.FTPReply;
  15. import com.scengine.wtms.utils.Log;
  16. public class FTPUtils
  17. {
  18. private FTPClient ftpClient = new FTPClient();
  19. /**
  20. * 对象构造 设置将过程中使用到的命令输出到控制台
  21. */
  22. public FTPUtils()
  23. {
  24. this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
  25. }
  26. /**
  27. *
  28. * java编程中用于连接到FTP服务器
  29. *
  30. * @param hostname
  31. * 主机名
  32. *
  33. * @param port
  34. * 端口
  35. *
  36. * @param username
  37. * 用户名
  38. *
  39. * @param password
  40. * 密码
  41. *
  42. * @return 是否连接成功
  43. *
  44. * @throws IOException
  45. */
  46. public boolean connect(String hostname, int port, String username, String password) throws IOException
  47. {
  48. ftpClient.connect(hostname, port);
  49. if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
  50. {
  51. if (ftpClient.login(username, password))
  52. {
  53. return true;
  54. }
  55. }
  56. disconnect();
  57. return false;
  58. }
  59. /**
  60. * 删除远程FTP文件
  61. *
  62. * @param remote
  63. * 远程文件路径
  64. * @return
  65. * @throws IOException
  66. */
  67. public FTPStatus delete(String remote) throws IOException
  68. {
  69. ftpClient.enterLocalPassiveMode();
  70. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  71. FTPStatus result = null;
  72. FTPFile[] files = ftpClient.listFiles(remote);
  73. if (files.length == 1)
  74. {
  75. boolean status = ftpClient.deleteFile(remote);
  76. result = status ? FTPStatus.Delete_Remote_Success : FTPStatus.Delete_Remote_Faild;
  77. }
  78. else
  79. {
  80. result = FTPStatus.Not_Exist_File;
  81. }
  82. Log.getLogger(this.getClass()).info("FTP服务器文件删除标识:"+result);
  83. return result;
  84. }
  85. /**
  86. * 重命名远程FTP文件
  87. *
  88. * @param name
  89. * 新远程文件名称(路径-必须保证在同一路径下)
  90. *
  91. * @param remote
  92. * 远程文件路径
  93. *
  94. * @return 是否成功
  95. *
  96. * @throws IOException
  97. */
  98. public FTPStatus rename(String name,String remote) throws IOException
  99. {
  100. ftpClient.enterLocalPassiveMode();
  101. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  102. FTPStatus result = null;
  103. FTPFile[] files = ftpClient.listFiles(remote);
  104. if (files.length == 1)
  105. {
  106. boolean status = ftpClient.rename(remote, name);
  107. result = status ? FTPStatus.Remote_Rename_Success : FTPStatus.Remote_Rename_Faild;
  108. }
  109. else
  110. {
  111. result = FTPStatus.Not_Exist_File;
  112. }
  113. Log.getLogger(this.getClass()).info("FTP服务器文件名更新标识:"+result);
  114. return result;
  115. }
  116. /**
  117. *
  118. * 从FTP服务器上下载文件
  119. *
  120. * @param fileName
  121. * 下载文件的名字(包括后缀名)
  122. *
  123. * @param remote
  124. * 远程文件路径
  125. *
  126. * @param local
  127. * 本地文件路径
  128. *
  129. * @return 是否成功
  130. *
  131. * @throws IOException
  132. */
  133. public FTPStatus download(String fileName,String remote,HttpServletResponse response) throws IOException
  134. {
  135. // 开启输出流弹出文件保存路径选择窗口
  136. response.setContentType("application/octet-stream");
  137. response.setContentType("application/OCTET-STREAM;charset=UTF-8");
  138. response.setHeader("Content-Disposition", "attachment;filename=" +fileName);
  139. ftpClient.enterLocalPassiveMode();
  140. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  141. FTPStatus result;
  142. OutputStream out = response.getOutputStream();
  143. boolean status = ftpClient.retrieveFile(remote, out);
  144. result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;
  145. Log.getLogger(this.getClass()).info("FTP服务器文件下载标识:"+result);
  146. out.close();
  147. return result;
  148. }
  149. /**
  150. *
  151. * 从FTP服务器上下载文件
  152. *
  153. * @param remote
  154. * 远程文件路径
  155. *
  156. * @param local
  157. * 本地文件路径
  158. *
  159. * @return 是否成功
  160. *
  161. * @throws IOException
  162. */
  163. @SuppressWarnings("resource")
  164. public FTPStatus download(String remote, String local) throws IOException
  165. {
  166. ftpClient.enterLocalPassiveMode();
  167. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  168. FTPStatus result;
  169. File f = new File(local);
  170. FTPFile[] files = ftpClient.listFiles(remote);
  171. if (files.length != 1)
  172. {
  173. Log.getLogger(this.getClass()).info("远程文件不唯一");
  174. return FTPStatus.File_Not_Unique;
  175. }
  176. long lRemoteSize = files[0].getSize();
  177. if (f.exists())
  178. {
  179. OutputStream out = new FileOutputStream(f, true);
  180. Log.getLogger(this.getClass()).info("本地文件大小为:" + f.length());
  181. if (f.length() >= lRemoteSize)
  182. {
  183. Log.getLogger(this.getClass()).info("本地文件大小大于远程文件大小,下载中止");
  184. return FTPStatus.Remote_smaller_local;
  185. }
  186. ftpClient.setRestartOffset(f.length());
  187. boolean status = ftpClient.retrieveFile(remote, out);
  188. result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;
  189. out.close();
  190. } else
  191. {
  192. OutputStream out = new FileOutputStream(f);
  193. boolean status = ftpClient.retrieveFile(remote, out);
  194. result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;
  195. out.close();
  196. }
  197. return result;
  198. }
  199. /**
  200. *
  201. * 上传文件到FTP服务器,支持断点续传
  202. *
  203. * @param local
  204. * 本地文件名称,绝对路径
  205. *
  206. * @param remote
  207. * 远程文件路径,使用/home/directory1/subdirectory/file.ext
  208. * 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
  209. *
  210. * @return 上传结果
  211. *
  212. * @throws IOException
  213. */
  214. @SuppressWarnings("resource")
  215. public FTPStatus upload(String local, String remote) throws IOException
  216. {
  217. // 设置PassiveMode传输
  218. ftpClient.enterLocalPassiveMode();
  219. // 设置以二进制流的方式传输
  220. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  221. FTPStatus result;
  222. // 对远程目录的处理
  223. String remoteFileName = remote;
  224. if (remote.contains("/"))
  225. {
  226. remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
  227. String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
  228. if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory))
  229. {
  230. // 如果远程目录不存在,则递归创建远程服务器目录
  231. int start = 0;
  232. int end = 0;
  233. if (directory.startsWith("/"))
  234. {
  235. start = 1;
  236. } else
  237. {
  238. start = 0;
  239. }
  240. end = directory.indexOf("/", start);
  241. while (true)
  242. {
  243. String subDirectory = remote.substring(start, end);
  244. if (!ftpClient.changeWorkingDirectory(subDirectory))
  245. {
  246. if (ftpClient.makeDirectory(subDirectory))
  247. {
  248. ftpClient.changeWorkingDirectory(subDirectory);
  249. } else
  250. {
  251. Log.getLogger(this.getClass()).info("创建目录失败");
  252. return FTPStatus.Create_Directory_Fail;
  253. }
  254. }
  255. start = end + 1;
  256. end = directory.indexOf("/", start);
  257. // 检查所有目录是否创建完毕
  258. if (end <= start)
  259. {
  260. break;
  261. }
  262. }
  263. }
  264. }
  265. // 检查远程是否存在文件
  266. FTPFile[] files = ftpClient.listFiles(remoteFileName);
  267. if (files.length == 1)
  268. {
  269. long remoteSize = files[0].getSize();
  270. File f = new File(local);
  271. long localSize = f.length();
  272. if (remoteSize == localSize)
  273. {
  274. return FTPStatus.File_Exits;
  275. } else if (remoteSize > localSize)
  276. {
  277. return FTPStatus.Remote_Bigger_Local;
  278. }
  279. // 尝试移动文件内读取指针,实现断点续传
  280. InputStream is = new FileInputStream(f);
  281. if (is.skip(remoteSize) == remoteSize)
  282. {
  283. ftpClient.setRestartOffset(remoteSize);
  284. if (ftpClient.storeFile(remote, is))
  285. {
  286. return FTPStatus.Upload_From_Break_Success;
  287. }
  288. }
  289. // 如果断点续传没有成功,则删除服务器上文件,重新上传
  290. if (!ftpClient.deleteFile(remoteFileName))
  291. {
  292. return FTPStatus.Delete_Remote_Faild;
  293. }
  294. is = new FileInputStream(f);
  295. if (ftpClient.storeFile(remote, is))
  296. {
  297. result = FTPStatus.Upload_New_File_Success;
  298. } else
  299. {
  300. result = FTPStatus.Upload_New_File_Failed;
  301. }
  302. is.close();
  303. } else
  304. {
  305. InputStream is = new FileInputStream(local);
  306. if (ftpClient.storeFile(remoteFileName, is))
  307. {
  308. result = FTPStatus.Upload_New_File_Success;
  309. } else
  310. {
  311. result = FTPStatus.Upload_New_File_Failed;
  312. }
  313. is.close();
  314. }
  315. return result;
  316. }
  317. /**
  318. *
  319. * 断开与远程服务器的连接
  320. *
  321. * @throws IOException
  322. */
  323. public void disconnect() throws IOException
  324. {
  325. if (ftpClient.isConnected())
  326. {
  327. ftpClient.disconnect();
  328. }
  329. }
  330. public static void main(String[] args)
  331. {
  332. FTPUtils myFtp = new FTPUtils();
  333. try
  334. {
  335. myFtp.connect("192.168.1.200", 21, "duser", "HTPDuserXP32");
  336. Log.getLogger(FTPUtils.class).info(myFtp.upload("C:\\Users\\Administrator\\Desktop\\swing.drawer.jar", "/jars/swing.drawer.jar"));
  337. myFtp.disconnect();
  338. } catch (IOException e)
  339. {
  340. Log.getLogger(FTPUtils.class).info("FTP上传文件异常:" + e.getMessage());
  341. }
  342. }
  343. }


相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载