1. username=admin
  2. password=123
  3. ip=192.168.14.117
  4. port=21

参考:http://blog.csdn.net/yelove1990/article/details/41245039
实现类

    1. package com.util;
    2. import java.io.*;
    3. import java.net.SocketException;
    4. import java.text.SimpleDateFormat;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import java.util.Properties;
    8. import org.apache.commons.logging.Log;
    9. import org.apache.commons.logging.LogFactory;
    10. import org.apache.commons.net.ftp.FTP;
    11. import org.apache.commons.net.ftp.FTPClient;
    12. import org.apache.commons.net.ftp.FTPClientConfig;
    13. import org.apache.commons.net.ftp.FTPFile;
    14. import org.apache.commons.net.ftp.FTPReply;
    15. public class FTPClientTest {
    16. private static final Log logger = LogFactory.getLog(FTPClientTest.class);
    17. private String userName;         //FTP 登录用户名
    18. private String password;         //FTP 登录密码
    19. private String ip;                     //FTP 服务器地址IP地址
    20. private int port;                        //FTP 端口
    21. private Properties property = null;    //属性集
    22. private String configFile = "conf/application.properties";    //配置文件的路径名
    23. private FTPClient ftpClient = null; //FTP 客户端代理
    24. //时间格式化
    25. private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    26. //FTP状态码
    27. public int i = 1;
    28. /**
    29. * 连接到服务器
    30. *
    31. * @return true 连接服务器成功,false 连接服务器失败
    32. */
    33. public boolean connectServer() {
    34. boolean flag = true;
    35. if (ftpClient == null) {
    36. int reply;
    37. try {
    38. if(setArg(configFile)){
    39. ftpClient = new FTPClient();
    40. ftpClient.setControlEncoding("GBK");
    41. //ftpClient.configure(getFtpConfig());
    42. ftpClient.connect(ip,port);
    43. ftpClient.login(userName, password);
    44. reply = ftpClient.getReplyCode();
    45. ftpClient.setDataTimeout(120000);
    46. if (!FTPReply.isPositiveCompletion(reply)) {
    47. ftpClient.disconnect();
    48. logger.debug("FTP 服务拒绝连接!");
    49. flag = false;
    50. }
    51. i++;
    52. }else{
    53. flag = false;
    54. }
    55. } catch (SocketException e) {
    56. flag = false;
    57. e.printStackTrace();
    58. logger.debug("登录ftp服务器 " + ip + " 失败,连接超时!");
    59. } catch (IOException e) {
    60. flag = false;
    61. e.printStackTrace();
    62. logger.debug("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");
    63. }
    64. }
    65. return flag;
    66. }
    67. /**
    68. * 上传文件
    69. *
    70. * @param remoteFile
    71. *            远程文件路径,支持多级目录嵌套
    72. * @param localFile
    73. *            本地文件名称,绝对路径
    74. *
    75. */
    76. public boolean uploadFile(String remoteFile, File localFile)
    77. throws IOException {
    78. boolean flag = false;
    79. InputStream in = new FileInputStream(localFile);
    80. String remote = new String(remoteFile.getBytes("GBK"),"iso-8859-1");
    81. if(ftpClient.storeFile(remote, in)){
    82. flag = true;
    83. logger.debug(localFile.getAbsolutePath()+"上传文件成功!");
    84. }else{
    85. logger.debug(localFile.getAbsolutePath()+"上传文件失败!");
    86. }
    87. in.close();
    88. return flag;
    89. }
    90. /**
    91. * 上传单个文件,并重命名
    92. *
    93. * @param localFile--本地文件路径
    94. * @param localRootFile--本地文件父文件夹路径
    95. * @param distFolder--新的文件名,可以命名为空""
    96. * @return true 上传成功,false 上传失败
    97. * @throws IOException
    98. */
    99. public boolean uploadFile(String local, String remote) throws IOException {
    100. boolean flag = true;
    101. String remoteFileName = remote;
    102. if (remote.contains("/")) {
    103. remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
    104. // 创建服务器远程目录结构,创建失败直接返回
    105. if (!CreateDirecroty(remote)) {
    106. return false;
    107. }
    108. }
    109. FTPFile[] files = ftpClient.listFiles(new String(remoteFileName));
    110. File f = new File(local);
    111. if(!uploadFile(remoteFileName, f)){
    112. flag = false;
    113. }
    114. return flag;
    115. }
    116. /**
    117. * 上传文件夹内的所有文件
    118. *
    119. *
    120. * @param filename
    121. *       本地文件夹绝对路径
    122. * @param uploadpath
    123. *       上传到FTP的路径,形式为/或/dir1/dir2/../
    124. * @return true 上传成功,false 上传失败
    125. * @throws IOException
    126. */
    127. public List uploadManyFile(String filename, String uploadpath) {
    128. boolean flag = true;
    129. List l = new ArrayList();
    130. StringBuffer strBuf = new StringBuffer();
    131. int n = 0; //上传失败的文件个数
    132. int m = 0; //上传成功的文件个数
    133. try {
    134. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    135. ftpClient.enterLocalPassiveMode();
    136. ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
    137. ftpClient.changeWorkingDirectory("/");
    138. File file = new File(filename);
    139. File fileList[] = file.listFiles();
    140. for (File upfile : fileList) {
    141. if (upfile.isDirectory()) {
    142. uploadManyFile(upfile.getAbsoluteFile().toString(),uploadpath);
    143. } else {
    144. String local = upfile.getCanonicalPath().replaceAll("\\\\","/");
    145. String remote = uploadpath.replaceAll("\\\\","/") + local.substring(local.indexOf("/") + 1);
    146. flag = uploadFile(local, remote);
    147. ftpClient.changeWorkingDirectory("/");
    148. }
    149. if (!flag) {
    150. n++;
    151. strBuf.append(upfile.getName() + ",");
    152. logger.debug("文件[" + upfile.getName() + "]上传失败");
    153. } else{
    154. m++;
    155. }
    156. }
    157. l.add(0, n);
    158. l.add(1, m);
    159. l.add(2, strBuf.toString());
    160. } catch (NullPointerException e) {
    161. e.printStackTrace();
    162. logger.debug("本地文件上传失败!找不到上传文件!", e);
    163. } catch (Exception e) {
    164. e.printStackTrace();
    165. logger.debug("本地文件上传失败!", e);
    166. }
    167. return l;
    168. }
    169. /**
    170. * 下载文件
    171. *
    172. * @param remoteFileName             --服务器上的文件名
    173. * @param localFileName--本地文件名
    174. * @return true 下载成功,false 下载失败
    175. */
    176. public boolean loadFile(String remoteFileName, String localFileName) {
    177. boolean flag = true;
    178. // 下载文件
    179. BufferedOutputStream buffOut = null;
    180. try {
    181. buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
    182. flag = ftpClient.retrieveFile(remoteFileName, buffOut);
    183. } catch (Exception e) {
    184. e.printStackTrace();
    185. logger.debug("本地文件下载失败!", e);
    186. } finally {
    187. try {
    188. if (buffOut != null)
    189. buffOut.close();
    190. } catch (Exception e) {
    191. e.printStackTrace();
    192. }
    193. }
    194. return flag;
    195. }
    196. /**
    197. * 删除一个文件
    198. */
    199. public boolean deleteFile(String filename) {
    200. boolean flag = true;
    201. try {
    202. flag = ftpClient.deleteFile(filename);
    203. if (flag) {
    204. logger.debug("删除文件"+filename+"成功!");
    205. } else {
    206. logger.debug("删除文件"+filename+"成功!");
    207. }
    208. } catch (IOException ioe) {
    209. ioe.printStackTrace();
    210. }
    211. return flag;
    212. }
    213. /**
    214. * 删除目录
    215. */
    216. public void deleteDirectory(String pathname) {
    217. try {
    218. File file = new File(pathname);
    219. if (file.isDirectory()) {
    220. File file2[] = file.listFiles();
    221. } else {
    222. deleteFile(pathname);
    223. }
    224. ftpClient.removeDirectory(pathname);
    225. } catch (IOException ioe) {
    226. ioe.printStackTrace();
    227. }
    228. }
    229. /**
    230. * 删除空目录
    231. */
    232. public void deleteEmptyDirectory(String pathname) {
    233. try {
    234. ftpClient.removeDirectory(pathname);
    235. } catch (IOException ioe) {
    236. ioe.printStackTrace();
    237. }
    238. }
    239. /**
    240. * 列出服务器上文件和目录
    241. *
    242. * @param regStr --匹配的正则表达式
    243. */
    244. public void listRemoteFiles(String regStr) {
    245. try {
    246. String files[] = ftpClient.listNames(regStr);
    247. if (files == null || files.length == 0)
    248. logger.debug("没有任何文件!");
    249. else {
    250. for (int i = 0; i < files.length; i++) {
    251. System.out.println(files[i]);
    252. }
    253. }
    254. } catch (Exception e) {
    255. e.printStackTrace();
    256. }
    257. }
    258. /**
    259. * 列出Ftp服务器上的所有文件和目录
    260. */
    261. public void listRemoteAllFiles() {
    262. try {
    263. String[] names = ftpClient.listNames();
    264. for (int i = 0; i < names.length; i++) {
    265. System.out.println(names[i]);
    266. }
    267. } catch (Exception e) {
    268. e.printStackTrace();
    269. }
    270. }
    271. /**
    272. * 关闭连接
    273. */
    274. public void closeConnect() {
    275. try {
    276. if (ftpClient != null) {
    277. ftpClient.logout();
    278. ftpClient.disconnect();
    279. }
    280. } catch (Exception e) {
    281. e.printStackTrace();
    282. }
    283. }
    284. /**
    285. * 设置传输文件的类型[文本文件或者二进制文件]
    286. *
    287. * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
    288. *
    289. */
    290. public void setFileType(int fileType) {
    291. try {
    292. ftpClient.setFileType(fileType);
    293. } catch (Exception e) {
    294. e.printStackTrace();
    295. }
    296. }
    297. /**
    298. * 设置参数
    299. *
    300. * @param configFile --参数的配置文件
    301. */
    302. private boolean setArg(String configFile) {
    303. boolean flag = true;
    304. property = new Properties();
    305. BufferedInputStream inBuff = null;
    306. try {
    307. inBuff = new BufferedInputStream(new FileInputStream(getClass().getResource("/").getPath() + configFile));
    308. property.load(inBuff);
    309. userName = property.getProperty("username");
    310. password = property.getProperty("password");
    311. ip = property.getProperty("ip");
    312. port = Integer.parseInt(property.getProperty("port"));
    313. } catch (FileNotFoundException e1) {
    314. flag = false;
    315. logger.debug("配置文件 " + configFile + " 不存在!");
    316. } catch (IOException e) {
    317. flag = false;
    318. logger.debug("配置文件 " + configFile + " 无法读取!");
    319. }
    320. return flag;
    321. }
    322. /**
    323. * 进入到服务器的某个目录下
    324. *
    325. * @param directory
    326. */
    327. public boolean changeWorkingDirectory(String directory) {
    328. boolean flag = true;
    329. try {
    330. flag = ftpClient.changeWorkingDirectory(directory);
    331. if (flag) {
    332. logger.debug("进入文件夹"+ directory + " 成功!");
    333. } else {
    334. logger.debug("进入文件夹"+ directory + " 失败!");
    335. }
    336. } catch (IOException ioe) {
    337. ioe.printStackTrace();
    338. }
    339. return flag;
    340. }
    341. /**
    342. * 返回到上一层目录
    343. */
    344. public void changeToParentDirectory() {
    345. try {
    346. ftpClient.changeToParentDirectory();
    347. } catch (IOException ioe) {
    348. ioe.printStackTrace();
    349. }
    350. }
    351. /**
    352. * 重命名文件
    353. *
    354. * @param oldFileName --原文件名
    355. * @param newFileName --新文件名
    356. */
    357. public void renameFile(String oldFileName, String newFileName) {
    358. try {
    359. ftpClient.rename(oldFileName, newFileName);
    360. } catch (IOException ioe) {
    361. ioe.printStackTrace();
    362. }
    363. }
    364. /**
    365. * 设置FTP客服端的配置--一般可以不设置
    366. *
    367. * @return ftpConfig
    368. */
    369. private FTPClientConfig getFtpConfig() {
    370. FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    371. ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
    372. return ftpConfig;
    373. }
    374. /**
    375. * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
    376. *
    377. * @param obj
    378. * @return ""
    379. */
    380. private String iso8859togbk(Object obj) {
    381. try {
    382. if (obj == null)
    383. return "";
    384. else
    385. return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
    386. } catch (Exception e) {
    387. return "";
    388. }
    389. }
    390. /**
    391. * 在服务器上创建一个文件夹
    392. *
    393. * @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
    394. */
    395. public boolean makeDirectory(String dir) {
    396. boolean flag = true;
    397. try {
    398. flag = ftpClient.makeDirectory(dir);
    399. if (flag) {
    400. logger.debug("创建文件夹"+ dir + " 成功!");
    401. } else {
    402. logger.debug("创建文件夹"+ dir + " 失败!");
    403. }
    404. } catch (Exception e) {
    405. e.printStackTrace();
    406. }
    407. return flag;
    408. }
    409. // 检查路径是否存在,存在返回true,否则false
    410. public boolean existFile(String path) throws IOException {
    411. boolean flag = false;
    412. FTPFile[] ftpFileArr = ftpClient.listFiles(path);
    413. /* for (FTPFile ftpFile : ftpFileArr) {
    414. if (ftpFile.isDirectory()
    415. && ftpFile.getName().equalsIgnoreCase(path)) {
    416. flag = true;
    417. break;
    418. }
    419. } */
    420. if(ftpFileArr.length > 0){
    421. flag = true;
    422. }
    423. return flag;
    424. }
    425. /**
    426. * 递归创建远程服务器目录
    427. *
    428. * @param remote
    429. *            远程服务器文件绝对路径
    430. *
    431. * @return 目录创建是否成功
    432. * @throws IOException
    433. */
    434. public boolean CreateDirecroty(String remote) throws IOException {
    435. boolean success = true;
    436. String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
    437. // 如果远程目录不存在,则递归创建远程服务器目录
    438. if (!directory.equalsIgnoreCase("/")&& !changeWorkingDirectory(new String(directory))) {
    439. int start = 0;
    440. int end = 0;
    441. if (directory.startsWith("/")) {
    442. start = 1;
    443. } else {
    444. start = 0;
    445. }
    446. end = directory.indexOf("/", start);
    447. while (true) {
    448. String subDirectory = new String(remote.substring(start, end).getBytes("GBK"),"iso-8859-1");
    449. if (changeWorkingDirectory(subDirectory)) {
    450. if (makeDirectory(subDirectory)) {
    451. changeWorkingDirectory(subDirectory);
    452. } else {
    453. logger.debug("创建目录["+subDirectory+"]失败");
    454. System.out.println("创建目录["+subDirectory+"]失败");
    455. success = false;
    456. return success;
    457. }
    458. }
    459. start = end + 1;
    460. end = directory.indexOf("/", start);
    461. // 检查所有目录是否创建完毕
    462. if (end <= start) {
    463. break;
    464. }
    465. }
    466. }
    467. return success;
    468. }
    469. public static void main(String[] args) {
    470. FTPClientTest ftpClient = new FTPClientTest();
    471. if(ftpClient.connectServer()){
    472. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件
    473. ftpClient.uploadManyFile("H:\\d", "/d/");
    474. ftpClient.closeConnect();// 关闭连接
    475. }
    476. }
    477. }

FTP之二的更多相关文章

  1. 8、FTP,二种文本传输模式

    一.基本知识 1. FTP是 TCP/IP协议族 的协议之一,简称文件传输协议,主要用于远距离文件传输,如文件的上传和下载 2. 下面都是以VSFTP服务器为例 VSFTP服务器的用户有三种形式: 匿 ...

  2. 使用c++实现一个FTP客户端(二)

    接上篇http://www.cnblogs.com/jzincnblogs/p/5213978.html,这篇主要记录编程方面的重点. 客户端使用了Windows Socket提供的API,支持上传. ...

  3. linux配置ftp

    参考: http://www.cnblogs.com/acpp/archive/2010/02/08/1665876.html http://blog.csdn.net/huzhenwei/artic ...

  4. FTP基础知识 FTP port(主动模式) pasv(被动模式) 及如何映射FTP

    您是否正准备搭建自己的FTP网站?您知道FTP协议的工作机制吗?您知道什么是PORT方式?什么是PASV方式吗?如果您不知道,或没有完全掌握,请您坐下来,花一点点时间,细心读完这篇文章.所谓磨刀不误砍 ...

  5. [转] Linux学习之CentOS(三十六)--FTP服务原理及vsfptd的安装、配置

    本篇随笔将讲解FTP服务的原理以及vsfptd这个最常用的FTP服务程序的安装与配置... 一.FTP服务原理 FTP(File Transfer Protocol)是一个非常古老并且应用十分广泛的文 ...

  6. linux Centos 6.5 FTP服务原理及vsfptd的安装、配置(转)

    本篇随笔将讲解FTP服务的原理以及vsfptd这个最常用的FTP服务程序的安装与配置... 一.FTP服务原理 FTP(File Transfer Protocol)是一个非常古老并且应用十分广泛的文 ...

  7. 【应用】:shell crontab定时生成oracle表的数据到txt文件,并上传到ftp

    一.本人环境描述      1.oracle服务端装在win7 32位上,oracle版本为10.2.0.1.0      2.Linux为centos6.5 32位,安装在Oracle VM Vir ...

  8. Sftp和ftp 差别、工作原理等(汇总ing)

    Sftp和ftp over ssh2的差别 近期使用SecureFx,涉及了两个不同的安全文件传输协议: -sftp -ftp over SSH2 这两种协议是不同的.sftp是ssh内含的协议,仅仅 ...

  9. wind7下搭建ftp服务器

    一.首先在本地机器上创建一个用户!这些用户是用来登录到FTP的!我的电脑右键->控制面板->管理工具->计算机管理->本地用户和组->用户->“右键”新建用户-&g ...

随机推荐

  1. A1138. Postorder Traversal

    Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and in ...

  2. A1131. Subway Map (30)

    In the big cities, the subway systems always look so complex to the visitors. To give you some sense ...

  3. vue2.0项目实战(5)vuex快速入门

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.Vuex 也集成到 Vue 的官方调试工具  ...

  4. poj1637 Sightseeing tour(混合图欧拉回路)

    题目链接 题意 给出一个混合图(有无向边,也有有向边),问能否通过确定无向边的方向,使得该图形成欧拉回路. 思路 这是一道混合图欧拉回路的模板题. 一张图要满足有欧拉回路,必须满足每个点的度数为偶数. ...

  5. 第十四节,卷积神经网络之经典网络Inception(四)

    一 1x1卷积 在架构内容设计方面,其中一个比较有帮助的想法是使用 1×1 卷积.也许你会好奇,1×1 的卷积能做什么呢?不就是乘以数字么?听上去挺好笑的,结果并非如此,我们来具体看看. 过滤器为 1 ...

  6. HTML学习笔记Day7

    一.position定位属性,检索对象的定位方式 1.语法:{position:static(无特殊定位)/absolute(绝对定位)/relative(相对定位)/fixed(固定定位):} 1) ...

  7. Luogu P2770 航空路线问题

    题目链接 \(Click\) \(Here\) 本来想调剂心情没想到写了那么久,还被\(dreagonm\)神仙嘲讽不会传纸条,我真是太弱了\(QAQ\)(原因:最开始写最大费用最大流一直想消圈,最后 ...

  8. (水题)P1424 小鱼的航程(改进版) 洛谷

    题目背景 原来的题目太简单,现改进让小鱼周末也休息,请已经做过重做该题. 题目描述 有一只小鱼,它上午游泳150公里,下午游泳100公里,晚上和周末都休息(实行双休日),假设从周x(1<=x&l ...

  9. threading:线程创建、启动、睡眠、退出

    1.方法一:将要执行的函数作为参数传递给threading.Thread() import threading import time def func(n): global count time.s ...

  10. mysql视图、触发事务、存储过程

    视图 视图是一个虚拟表(非真实存在的),其本质就是根据SQL语言获取动态的数据集,并为其命名,用户使用时只需要使用名称即可获得结果集,可以将结果集当做表来使用. 视图是存在数据库中的,如果我们程序中使 ...