1. package comm.ftp;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8.  
  9. import org.apache.commons.net.ftp.FTP;
  10. import org.apache.commons.net.ftp.FTPClient;
  11. import org.apache.commons.net.ftp.FTPClientConfig;
  12. import org.apache.commons.net.ftp.FTPFile;
  13. import org.apache.commons.net.ftp.FTPReply;
  14.  
  15. /**
  16. * 该类为FTP相关的工具类
  17. *
  18. * @author wxq
  19. *
  20. */
  21. public class FtpUtil {
  22. FTPClientConfig config = null;
  23. FTPClient ftpClient = null;
  24. String serverIp = "";// ftp服务器ip地址
  25. int serverPort = 0;// ftp服务器端口
  26. String usrName = "";// ftp用户名
  27. String usrPwd = "";// ftp用户密码
  28. String baseWorkDirectory = "";// 基本工作目录
  29. int fileType = FTP.BINARY_FILE_TYPE;// 上传下载文件方式,默认使用二进制流
  30. // 本地编码字符串编码
  31. String localCharset = "UTF-8";
  32. // FTP服务器端字符串编码
  33. String serverCharset = "ISO-8859-1";
  34.  
  35. public FtpUtil(String serverIp, int serverPort, String usrName,
  36. String usrPwd, String baseWorkDirectory, int fileType) {
  37. super();
  38. this.serverIp = serverIp;
  39. this.serverPort = serverPort;
  40. this.usrName = usrName;
  41. this.usrPwd = usrPwd;
  42. this.baseWorkDirectory = baseWorkDirectory;
  43. this.fileType = fileType;
  44. }
  45.  
  46. /**
  47. * 使用默认值,生成FTPClientConfig对象
  48. */
  49. public void setFtpClientConfigByDefault() {
  50. config = new FTPClientConfig();
  51. }
  52.  
  53. /**
  54. * 使用参数指定的值生成FTPClientConfig对象
  55. *
  56. * @param isParamsActived
  57. * 标记是否使用后面参数,false则不使用,且使用默认值构造一个FTPClientConfig对象
  58. * @param osType
  59. * FTPClientConfig.SYST_NT FTPClientConfig.SYST_UNIX
  60. * @param serverLanguageCode
  61. * @param defaultDateFormatStr
  62. * @param recentDateFormatStr
  63. * @param serverTimeZoneId
  64. * @return
  65. */
  66. public void setFtpClientConfig(String osType, String serverLanguageCode,
  67. String defaultDateFormatStr, String recentDateFormatStr,
  68. String serverTimeZoneId) {
  69. try {
  70. if (!osType.equals("")) {
  71. config = new FTPClientConfig(osType);
  72. }
  73. if (!serverLanguageCode.equals("")) {
  74. config.setServerLanguageCode(serverLanguageCode);
  75. }
  76. if (!defaultDateFormatStr.equals("")) {
  77.  
  78. config.setDefaultDateFormatStr(defaultDateFormatStr);
  79. }
  80. if (!recentDateFormatStr.equals("")) {
  81.  
  82. config.setRecentDateFormatStr(recentDateFormatStr);
  83. }
  84. if (!serverTimeZoneId.equals("")) {
  85.  
  86. config.setServerTimeZoneId(serverTimeZoneId);
  87. }
  88.  
  89. } catch (Exception e) {
  90. // TODO: handle exception
  91. e.printStackTrace();
  92. }
  93. }
  94.  
  95. /**
  96. * 连接FTP服务器,并登录,切换至基本工作目录(通常为当前用户的根目录)
  97. *
  98. */
  99. public void connectServer() {
  100. try {
  101. ftpClient = new FTPClient();
  102. if (config != null) {
  103. ftpClient.configure(config);
  104. int reply;
  105. ftpClient.connect(serverIp, serverPort);
  106. reply = ftpClient.getReplyCode();
  107. if (!FTPReply.isPositiveCompletion(reply)) {
  108. ftpClient.disconnect();
  109. System.out.println("FTP server refused connection");
  110. } else {
  111. // set file type
  112. // ftpClient.setFileType(fileType);
  113. if (ftpClient.login(usrName, usrPwd)) {
  114. System.out.println("login success");
  115. }
  116. ftpClient.changeWorkingDirectory(baseWorkDirectory);
  117. }
  118. }
  119. } catch (Exception e) {
  120. // TODO Auto-generated catch block
  121. e.printStackTrace();
  122. if (ftpClient.isConnected()) {
  123. try {
  124. ftpClient.disconnect();
  125. } catch (IOException e1) {
  126. // TODO Auto-generated catch block
  127. e1.printStackTrace();
  128. }
  129. }
  130. }
  131. }
  132.  
  133. /**
  134. * 上传文件至Ftp用户根目录下的指定目录,如果subDirectory.equals("")为true, 则上传文件存放到当前用户的根目录
  135. *
  136. * @param subDirectory
  137. * 子目录
  138. * @param storeName
  139. * 上传文件在FTP服务器上的存储名字
  140. * @param file
  141. * 上传文件
  142. * @return
  143. */
  144. public boolean uploadFileToFtpServer(String subDirectory, String storeName,
  145. File file) {
  146. // 上传文件成功标记
  147. boolean isUploadSuccess = false;
  148. FileInputStream fin = null;
  149. try {
  150. if (file.exists()) {
  151. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  152. storeName=new String(storeName.getBytes(localCharset),serverCharset);
  153. storeName = new String(storeName.getBytes(localCharset),
  154. serverCharset);
  155. storeName = this.handleStoreName(subDirectory, storeName);
  156. fin = new FileInputStream(file);
  157. // Stores a file on the server using the given name and taking
  158. // input from the given InputStream.
  159. if (ftpClient.storeFile(storeName, fin)) {
  160. isUploadSuccess = true;
  161. System.out.println("upload file to FTP server success");
  162. }
  163. } else {
  164. System.out.println("upload file does not exsit");
  165. }
  166. } catch (Exception e) {
  167. // TODO: handle exception
  168. e.printStackTrace();
  169. } finally {
  170. if (fin != null) {
  171. try {
  172. fin.close();
  173. } catch (IOException e) {
  174. // TODO Auto-generated catch block
  175. e.printStackTrace();
  176. }
  177. }
  178. }
  179. return isUploadSuccess;
  180. }
  181.  
  182. /**
  183. * 上传字符串至Ftp用户根目录下的指定目录下的指定文件,如果subDirectory.equals("")为true,
  184. * 则上传文件存放到当前用户的根目录
  185. *
  186. * @param subDirectory
  187. * 子目录,
  188. * @param storeName
  189. * 上传的字符串在FTP服务器上存储文件的名字
  190. * @param uploadStr
  191. * 上传的字符串
  192. * @return
  193. */
  194. public boolean uploadStringToFtpServer(String subDirectory,
  195. String storeName, String uploadStr) {
  196. // 上传成功标记
  197. boolean isUploadSuccess = false;
  198. ByteArrayInputStream bais = null;
  199. try {
  200. if (uploadStr != null) {
  201. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  202. storeName=new String(storeName.getBytes(localCharset),serverCharset);
  203. storeName = this.handleStoreName(subDirectory, storeName);
  204. bais = new ByteArrayInputStream(uploadStr.getBytes());
  205. // Stores a file on the server using the given name and taking
  206. // input from the given InputStream.
  207. if (ftpClient.storeFile(storeName, bais)) {
  208. isUploadSuccess = true;
  209. System.out.println("upload String to FTP server success");
  210. }
  211. } else {
  212. System.out.println("upload String is null");
  213. }
  214. } catch (Exception e) {
  215. // TODO: handle exception
  216. e.printStackTrace();
  217. } finally {
  218. if (bais != null) {
  219. try {
  220. bais.close();
  221. } catch (IOException e) {
  222. // TODO Auto-generated catch block
  223. e.printStackTrace();
  224. }
  225. }
  226. }
  227. return isUploadSuccess;
  228. }
  229.  
  230. /**
  231. * 从FTP服务器下载文件到本地指定路径,当subDirectory.equals("")时,则在当前用户的根目录下去找要下载的文件
  232. *
  233. * @param subDirectory
  234. * ftp服务器上存放要下载文件的子目录
  235. * @param fileName
  236. * 下载文件的名字
  237. * @param localPath
  238. * 本地存放路径
  239. * @return 下载成功,返回true
  240. */
  241. public boolean downFileFromFtpServer(String subDirectory, String fileName,
  242. String localPath) {
  243. FileOutputStream fos = null;
  244. boolean isDownloadSuccess = false;
  245. try {
  246. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  247. String baseWorkDir = ftpClient.printWorkingDirectory();
  248. if (!subDirectory.equals("")) {
  249. baseWorkDir = baseWorkDir + "/" + subDirectory;
  250. }
  251. ftpClient.changeWorkingDirectory(baseWorkDir);
  252.  
  253. fos = new FileOutputStream(localPath + "/" + fileName);
  254. fileName = new String(fileName.getBytes(localCharset),
  255. serverCharset);
  256. // Retrieves a named file from the server and writes it to the given
  257. // OutputStream.
  258. if (ftpClient.retrieveFile(fileName, fos)) {
  259. isDownloadSuccess = true;
  260. System.out.println("download from FTP server success");
  261. }
  262. } catch (Exception e) {
  263. // TODO Auto-generated catch block
  264. e.printStackTrace();
  265. } finally {
  266. if (fos != null) {
  267. try {
  268. fos.close();
  269. } catch (IOException e) {
  270. // TODO Auto-generated catch block
  271. e.printStackTrace();
  272. }
  273. }
  274. }
  275. return isDownloadSuccess;
  276. }
  277.  
  278. /**
  279. * 下载Ftp服务器上指定目录下的所有文件(不包含文件夹)到本机的指定目录,子目录subDirectory.equals("")时, 则指定目录就是用户的根目录
  280. *
  281. * @param subDirectory
  282. * ftp服务器上包含文件的子目录
  283. * @param localPath
  284. * @return
  285. */
  286. public boolean downloadFilesFromFtpServer(String subDirectory,
  287. String localPath) {
  288. boolean isDownloadSuccess = false;
  289. FileOutputStream fos = null;
  290. try {
  291. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  292. String baseWorkDir = ftpClient.printWorkingDirectory();
  293. if (!subDirectory.equals("")) {
  294. baseWorkDir = baseWorkDir + "/" + subDirectory;
  295. }
  296. ftpClient.changeWorkingDirectory(baseWorkDir);
  297. FTPFile[] files = ftpClient.listFiles();
  298. if (files != null && files.length > 0) {
  299. // 下载目录下所有文件
  300. for (FTPFile file : files) {
  301. if(file.isFile()){
  302. String fileName = new String(file.getName().getBytes(
  303. serverCharset), localCharset);
  304. fos = new FileOutputStream(localPath + "/" + fileName);
  305. if (ftpClient.retrieveFile(file.getName(), fos)) {
  306. System.out.println("download file: " + fileName
  307. + " success");
  308. }
  309. fos.flush();
  310. }
  311. }
  312. }
  313. isDownloadSuccess = true;
  314. } catch (Exception e) {
  315. // TODO Auto-generated catch block
  316. e.printStackTrace();
  317. } finally {
  318. if (fos != null) {
  319. try {
  320. fos.close();
  321. } catch (IOException e) {
  322. // TODO Auto-generated catch block
  323. e.printStackTrace();
  324. }
  325. }
  326. }
  327. return isDownloadSuccess;
  328. }
  329.  
  330. /**
  331. * 删除ftp服务器上的指定目录下的某个文件
  332. *
  333. * @param subDirectory
  334. * 子目录
  335. * @param fileName
  336. * 文件名
  337. * @return 删除成功,返回true
  338. */
  339. public boolean deleteFileInFtpServer(String subDirectory, String fileName) {
  340. boolean isDeleteSuccess = false;
  341. try {
  342. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  343. fileName = new String(fileName.getBytes(localCharset),
  344. serverCharset);
  345. fileName = this.handleStoreName(subDirectory, fileName);
  346. if (ftpClient.deleteFile(fileName)) {
  347. isDeleteSuccess = true;
  348. System.out.println("delete file on ftp server success");
  349. } else {
  350. System.out.println("delete file on ftp server fail");
  351. }
  352. } catch (IOException e) {
  353. // TODO Auto-generated catch block
  354. e.printStackTrace();
  355. }
  356. return isDeleteSuccess;
  357. }
  358.  
  359. /**
  360. * 删除指定目录下的所有文件,如果folderName为“”,则删除subDirectory下的所有文件(不包括文件夹)。
  361. *
  362. * @param subDirectory
  363. * 子目录
  364. * @param folderName
  365. * 文件夹名称
  366. * @return
  367. */
  368. public boolean deleteFilesInFtpServer(String subDirectory, String folderName) {
  369. boolean isDeleteSuccess = false;
  370. try {
  371. String baseWorkDir = ftpClient.printWorkingDirectory();
  372. if (!subDirectory.equals("")) {
  373. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  374. baseWorkDir = baseWorkDir + "/" + subDirectory;
  375. }
  376. if (!folderName.equals("")) {
  377. folderName=new String(folderName.getBytes(localCharset),serverCharset);
  378. baseWorkDir = baseWorkDir + "/" + folderName;
  379. }
  380. ftpClient.changeWorkingDirectory(baseWorkDir);
  381. FTPFile[] files = ftpClient.listFiles();
  382. if (files != null) {
  383. for (FTPFile file : files) {
  384. ftpClient.deleteFile(file.getName());
  385. }
  386. isDeleteSuccess=true;
  387. }
  388. System.out.println("delete files in ftp server success");
  389. } catch (IOException e) {
  390. // TODO Auto-generated catch block
  391. System.out.println("delete files in ftp server exception: "+e.getMessage());
  392. }
  393. return isDeleteSuccess;
  394. }
  395.  
  396. /**
  397. * 在用户的根目录下创建指定文件夹,如果subDirectory是一个目录则依次创建各级文件夹。如果文件夹存在,则返回false
  398. *
  399. * @param subDirectory
  400. * 子目录
  401. * @return 成功返回true
  402. */
  403. public boolean createDirInBaseWorkDir(String subDirectory) {
  404. boolean isCreateSuccess = false;
  405. try {
  406. if (!subDirectory.equals("")) {
  407. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  408. if (ftpClient.makeDirectory(subDirectory)) {
  409. isCreateSuccess = true;
  410. System.out
  411. .println("create new directory in base work directory success");
  412. } else {
  413. System.out
  414. .println("create new directory fail,the directory exsited");
  415. }
  416. }
  417. } catch (IOException e) {
  418. // TODO Auto-generated catch block
  419. e.printStackTrace();
  420. }
  421. return isCreateSuccess;
  422. }
  423.  
  424. /**
  425. * 删除用户根目录下的指定文件夹,如果subDirectory是一个路径,则删除最低级的那个文件夹;如果文件夹不存在则返回false。
  426. * 如果文件夹不为空,则返回false
  427. *
  428. * @param subDirectory
  429. * @return
  430. */
  431. public boolean rmDirInBaseWorkDir(String subDirectory) {
  432. boolean isRmDirSuccess = false;
  433. try {
  434. subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
  435. if (ftpClient.removeDirectory(subDirectory)) {
  436. isRmDirSuccess = true;
  437. System.out
  438. .println("remove directory in base work directory success");
  439. } else {
  440. System.out
  441. .println("remove directory in base work directory fail");
  442. }
  443. } catch (IOException e) {
  444. // TODO Auto-generated catch block
  445. e.printStackTrace();
  446. }
  447. return isRmDirSuccess;
  448. }
  449.  
  450. /**
  451. * 该方法用于处理文件时,对子目录和文件名进行处理
  452. *
  453. * @param subDirectory
  454. * 子目录
  455. * @param storeName
  456. * 文件名
  457. * @return 返回处理后可能带有路径的文件名
  458. */
  459. private String handleStoreName(String subDirectory, String storeName) {
  460. // 子目录是否存在标记
  461. boolean isSubDirectoryExsit = false;
  462. try {
  463. // 此处判断是否要生成子目录,存在则不创建
  464. FTPFile[] dirs = ftpClient.listDirectories();
  465. if (dirs != null && dirs.length > 0) {
  466. for (int i = 0; i < dirs.length; i++) {
  467. if (dirs[i].getName().equals(subDirectory)) {
  468. isSubDirectoryExsit = true;
  469. }
  470. break;
  471. }
  472. }
  473. dirs = null;
  474. if (!isSubDirectoryExsit && !subDirectory.equals("")) {
  475. ftpClient.makeDirectory(subDirectory);
  476. storeName = subDirectory + "/" + storeName;
  477. }
  478. if (isSubDirectoryExsit && !subDirectory.equals("")) {
  479. storeName = subDirectory + "/" + storeName;
  480. }
  481. } catch (IOException e) {
  482. // TODO Auto-generated catch block
  483. e.printStackTrace();
  484. }
  485. return storeName;
  486. }
  487.  
  488. }

java 操作FTP的更多相关文章

  1. java操作FTP的一些工具方法

    java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...

  2. Java操作FTP工具类(实例详解)

    这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包  工具类 package com.zit.ftp; import java.io.File; import java.i ...

  3. java操作FTP,实现文件上传下载删除操作

    上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...

  4. Java操作FTP,从FTP上读取指定文件,把指定文件上传到FTP

    需要添加的依赖 <!-- https://mvnrepository.com/artifact/commons-net/commons-net --> <dependency> ...

  5. Java实现FTP跨服务器文件操作

    在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传.文件下载.文件删除等.跨服务器文件操作一般是需要FT ...

  6. Java实现FTP文件与文件夹的上传和下载

    Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...

  7. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  8. 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等

    记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...

  9. Java操作Sqlite数据库-jdbc连接

    Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...

随机推荐

  1. Ionic android 底部tabs

    ionic android tabs 默认显示在上部,如果要跟苹果一起统一在底部,那么可以在app.js添加配置 .config(function($ionicConfigProvider) { $i ...

  2. Android Crash 全局捕获

    Android Crash 全局捕获 首先应该明白的一点是,Android在崩溃后会重新启动崩溃时的那个Activity,如果你的Activity在初始化的时候就直接崩溃,那么你将连续得到 Crash ...

  3. python 接口自动化测试(四)

    说完了SOAP协议的接口自动化 该说下http协议的接口测试了 HttpService.py import requests import sys reload(sys) sys.setdefault ...

  4. shiro学习笔记_0100_shiro简介

    前言:第一次知道shiro是2016年夏天,做项目时候我要写springmvc的拦截器,申哥看到后,说这个不安全,就给我捣鼓了shiro,我就看了下,从此认识了shiro.此笔记是根据网上的视频教程记 ...

  5. java中String s = new String("abc")创建了几个对象?

    答案是两个,现在我们具体的说一下: String s = new String("abc");一.我们要明白两个概念,引用变量和对象,对象一般通过new在堆中创建,s只是一个引用变 ...

  6. 二级C考点汇总

    1.变量命名的合法性2.数据类型的转换,分为强类型和隐式类型3.字符串:字符串的声明.定义和使用,通常结合数组和指针 4.数组:下标的转换及数组的顺序存储5.函数:声明.定义.调用,递归函数(如菲薄纳 ...

  7. Bootstrap 组件之 Navbar

    一.简介 Navbar 指导航条,它在移动设备上显示为折叠状态,在宽屏幕上水平展开.这里 是一个线上例子. 响应式导航条依赖 collapse 插件,定制 Bootstrap 时务必要包含. {设备的 ...

  8. python复习。知识点小记

    1.对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符: >>> ord('A') >>> ord('中' ...

  9. 使用github+hexo搭建博客笔记

    听说github上可以搭博客,而且不用自己提供空间和维护,哈哈哈 作为一名程序猿,github搭博客对我有种神奇的吸引力,赶紧动手试一试 关于如何使用hexo搭建博客网上好的教程多如牛毛,而且这篇博客 ...

  10. 自适应滤波:最小均方误差滤波器(LMS、NLMS)

    作者:桂. 时间:2017-04-02  08:08:31 链接:http://www.cnblogs.com/xingshansi/p/6658203.html 声明:欢迎被转载,不过记得注明出处哦 ...