1. package net.util.common;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import org.apache.commons.net.ftp.FTPClient;
  11. import org.apache.commons.net.ftp.FTPFile;
  12. import org.apache.commons.net.ftp.FTPReply;
  13. import org.apache.commons.net.ftp.FTPSClient;
  14.  
  15. /**
  16. * need commons-net-3.5.jar
  17. */
  18. public class FtpHelper {
  19.  
  20. private String host;//ip地址
  21. private Integer port;//端口号
  22. private String userName;//用户名
  23. private String pwd;//密码
  24. //private String homePath;//aaa路径
  25. private String charSet = "utf-8";
  26. // 默认超时, 毫秒
  27. private long timeout = 30*1000;
  28.  
  29. public FTPClient ftpClient = null;
  30.  
  31. public FtpHelper(){
  32. init();
  33. }
  34. public FtpHelper(boolean ftps){
  35. init(ftps);
  36. }
  37.  
  38. /**
  39. * ftp 初始化
  40. */
  41. public void init(){
  42. init(false);
  43. }
  44. public void init(boolean ftps){
  45. close();
  46. if(ftps==true){
  47. ftpClient = new FTPSClient(true);
  48. }
  49. else{
  50. ftpClient=new FTPClient();
  51. }
  52.  
  53. // 默认编码
  54. ftpClient.setControlEncoding(charSet);
  55.  
  56. //ftpClient.setBufferSize(524288);
  57. //ftpClient.enterLocalPassiveMode();
  58. // 毫秒计时
  59. ftpClient.setDefaultTimeout((int) timeout);
  60. ftpClient.setConnectTimeout((int) timeout);
  61. //ftpClient.setSoTimeout((int) timeout);
  62. //ftpClient.setDataTimeout(timeout);
  63. }
  64.  
  65. /**
  66. * 获取ftp连接
  67. * @return
  68. * @throws Exception
  69. */
  70. public boolean connect(String host, Integer port, String userName, String pwd) throws Exception{
  71. this.host = host;
  72. this.port = port;
  73. this.userName= userName;
  74. this.pwd = pwd;
  75. return connect();
  76. }
  77. public boolean connect() throws Exception{
  78. boolean flag=false;
  79. int reply;
  80. if (port==null) {
  81. ftpClient.connect(host,21);
  82. }else{
  83. ftpClient.connect(host, port);
  84. }
  85.  
  86. flag = ftpClient.login(userName, pwd);
  87. if(flag==false)
  88. return flag;
  89.  
  90. // 服务器是否响应
  91. reply = ftpClient.getReplyCode();
  92. if (FTPReply.isPositiveCompletion(reply)==false) {
  93. flag = false;
  94. ftpClient.disconnect();
  95. return flag;
  96. }
  97.  
  98. // 默认文件格式
  99. ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
  100. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  101.  
  102. return flag;
  103. }
  104.  
  105. /**
  106. * 关闭ftp连接
  107. */
  108. public void close(){
  109. if (ftpClient==null || ftpClient.isConnected()==false) {
  110. ftpClient = null;
  111. return;
  112. }
  113. try {
  114. ftpClient.logout();
  115. ftpClient.disconnect();
  116. } catch (IOException e) {
  117. LogHelper.logger.warn("",e);
  118. }
  119. ftpClient = null;
  120. }
  121.  
  122. /*
  123. * ftp 多种开关函数
  124. */
  125. public FTPClient getClient(){
  126. return ftpClient;
  127. }
  128. public void setControlEncoding(String encoding) {
  129. this.charSet = encoding;
  130. ftpClient.setControlEncoding(encoding);
  131. }
  132. public void enterLocalPassiveMode(){
  133. ftpClient.enterLocalPassiveMode();
  134. }
  135. public void enterLocalActiveMode(){
  136. ftpClient.enterLocalActiveMode();
  137. }
  138. // 毫秒计时
  139. public void setDefaultTimeout(int timeout) {
  140. ftpClient.setDefaultTimeout(timeout);
  141. }
  142. // 毫秒计时
  143. // public void setConnectTimeout(int connectTimeout) {
  144. // ftpClient.setConnectTimeout(connectTimeout);
  145. // }
  146. // 毫秒计时
  147. public void setDataTimeout(int timeout) {
  148. ftpClient.setDataTimeout(timeout);
  149. }
  150. public void setBufferSize(int bufSize) {
  151. ftpClient.setBufferSize(bufSize);
  152. }
  153. /**
  154. * 传输格式
  155. * @param mode: FTPClient.BINARY_FILE_TYPE
  156. * @return
  157. * @throws IOException
  158. */
  159. public boolean setFileTransferMode(int mode) throws IOException{
  160. return ftpClient.setFileTransferMode(mode);
  161. }
  162. /**
  163. * 文件格式
  164. * @param mode: FTPClient.BINARY_FILE_TYPE
  165. * @return
  166. * @throws IOException
  167. */
  168. public boolean setFileType(int mode) throws IOException {
  169. return ftpClient.setFileType(mode);
  170.  
  171. }
  172. /*
  173. * ftp 多种开关函数
  174. */
  175.  
  176. /**
  177. * ftp创建目录
  178. * @param path
  179. * @return
  180. * @throws IOException
  181. */
  182. public boolean createDir(String path) throws IOException{
  183. boolean bl = false;
  184. String pwd = "/";
  185. try {
  186. pwd = ftpClient.printWorkingDirectory();
  187. } catch (IOException e) {
  188. LogHelper.logger.warn("",e);
  189. }
  190. if(path.endsWith("/")==false){
  191. path = path + "/";
  192. }
  193. int fromIndex = 0;
  194. while(true){
  195. int start = path.indexOf("/", fromIndex);
  196. if(start<0)
  197. break;
  198. fromIndex = start;
  199. String curPath = path.substring(0, fromIndex+1);
  200. //System.out.println(curPath);
  201. bl = ftpClient.changeWorkingDirectory(curPath);
  202. if(bl==false){
  203. bl = ftpClient.makeDirectory(curPath);
  204. }
  205. if(bl==false)
  206. break;
  207. fromIndex = fromIndex + 1;
  208. }
  209. ftpClient.changeWorkingDirectory(pwd);
  210. return bl;
  211. }
  212.  
  213. /**
  214. * ftp上传文件或文件夹
  215. * @param srcPath: 本地目录或文件
  216. * @param dstPath: ftp目录或文件
  217. * @throws Exception
  218. */
  219. public void upload(String localPath, String ftpPath) throws Exception{
  220. File file = new File(localPath);
  221. if (file.isDirectory()) {
  222. createDir(ftpPath);
  223. String[] files=file.list();
  224. for(String fileName : files){
  225. String subLocalPath = PathUtil.CombineUrl(localPath, fileName);
  226. String subFtpPath = PathUtil.CombineUrl(ftpPath, fileName);
  227. upload(subLocalPath, subFtpPath);
  228. }
  229. }
  230. else{
  231. FileInputStream localInput = null;
  232. try {
  233. //ftpClient.enterLocalPassiveMode();
  234. String dirPath = new File(ftpPath).getParent();
  235. dirPath = dirPath.replace("\\", "/");
  236. createDir(dirPath);
  237. localInput = new FileInputStream(file);
  238. if(ftpClient.storeFile(ftpPath, localInput)==false){
  239. LogHelper.logger.error("ftp upload file error: "+localPath);
  240. }
  241. }
  242. catch (Exception e) {
  243. LogHelper.logger.warn("",e);
  244. }
  245. finally{
  246. try {
  247. if(localInput!=null)
  248. localInput.close();
  249. } catch (Exception e) {}
  250. }
  251. }
  252. }
  253. /**
  254. * ftp单文件上传
  255. * @param localPath
  256. * @param ftpPath
  257. * @return
  258. */
  259. public boolean uploadFile(String localPath, String ftpPath){
  260. boolean bl = false;
  261. File file = new File(localPath);
  262. if (file.isFile()) {
  263. FileInputStream localInput = null;
  264. try {
  265. //String tmpPath = ftpPath + ".tmp";
  266. //ftpClient.enterLocalPassiveMode();
  267. String dirPath = new File(ftpPath).getParent();
  268. dirPath = dirPath.replace("\\", "/");
  269. createDir(dirPath);
  270. localInput = new FileInputStream(file);
  271. if(ftpClient.storeFile(ftpPath, localInput)==false){
  272. bl = false;
  273. LogHelper.logger.error("ftp upload file error: "+localPath);
  274. }
  275. else{
  276. //bl = ftpClient.rename(tmpPath, ftpPath);
  277. bl = true;
  278. }
  279. }
  280. catch (Exception e) {
  281. LogHelper.logger.warn("",e);
  282. }
  283. finally{
  284. try {
  285. if(localInput!=null)
  286. localInput.close();
  287. } catch (Exception e) {}
  288. }
  289. }
  290. return bl;
  291. }
  292.  
  293. /**
  294. * ftp下载文件或目录
  295. * @param ftpPath: ftp远程目录或文件
  296. * @param localPath: 本地保存目录或文件
  297. * @param isFile: ftppath是文件或目录
  298. * @throws Exception
  299. */
  300. public void down(String ftpPath, String localPath, boolean isFile) throws Exception{
  301. if(isFile==true){
  302. FileOutputStream localFos = null;
  303. try {
  304. //ftpClient.enterLocalPassiveMode();
  305. String dirPath = new File(localPath).getParent();
  306. FileUtil.createDir(dirPath);
  307. File file = new File(localPath);
  308. localFos = new FileOutputStream(file);
  309. if(ftpClient.retrieveFile(ftpPath, localFos)==false){
  310. LogHelper.logger.error("ftp down file error: "+ftpPath);
  311. }
  312. }
  313. catch (Exception e) {
  314. LogHelper.logger.warn("",e);
  315. }
  316. finally{
  317. try {
  318. if(localFos!=null)
  319. localFos.close();
  320. } catch (Exception e) {}
  321. }
  322. }
  323. // 目录处理
  324. else{
  325. FileUtil.createDir(localPath);
  326. FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath);
  327. for (int j=0; j<ftpFiles.length; j++) {
  328. FTPFile ftpFile = ftpFiles[j];
  329. String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName());
  330. String subLocalPath = PathUtil.CombineUrl(localPath, ftpFile.getName());
  331. if(ftpFile.isFile()==true){
  332. down(subFtpPath, subLocalPath, true);
  333. }
  334. else{
  335. down(subFtpPath, subLocalPath, false);
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * ftp单文件下载
  342. * @param ftpPath
  343. * @param localPath
  344. * @return
  345. */
  346. public boolean downFile(String ftpPath, String localPath) {
  347. boolean bl = false;
  348. FileOutputStream localFos = null;
  349. try {
  350. //ftpClient.enterLocalPassiveMode();
  351. FileUtil.createDir(localPath, true);
  352. File file = new File(localPath);
  353. localFos = new FileOutputStream(file);
  354. if(ftpClient.retrieveFile(ftpPath, localFos)==false){
  355. LogHelper.logger.error("ftp down file error: "+ftpPath);
  356. }
  357. else{
  358. bl = true;
  359. }
  360. }
  361. catch (Exception e) {
  362. LogHelper.logger.warn("",e);
  363. }
  364. finally{
  365. try {
  366. if(localFos!=null)
  367. localFos.close();
  368. } catch (Exception e) {}
  369. }
  370. return bl;
  371. }
  372.  
  373. /**
  374. * 判断路径是否为ftp文件
  375. * @param ftpPath
  376. * @return
  377. * @throws IOException
  378. */
  379. public boolean isFile(String ftpPath) throws IOException{
  380. if(ftpPath==null || ftpPath.endsWith("/"))
  381. return false;
  382. File f = new File(ftpPath);
  383. String lastName = f.getName();
  384. String parentDir = f.getParent();
  385. // 根目录没有上层目录
  386. if(parentDir==null)
  387. return false;
  388. FTPFile[] ftpFiles = ftpClient.listFiles(parentDir);
  389. for (int j=0; j<ftpFiles.length; j++) {
  390. FTPFile ftpFile = ftpFiles[j];
  391. if(ftpFile.isFile()==true && lastName.equals(ftpFile.getName())){
  392. return true;
  393. }
  394. }
  395. return false;
  396. }
  397. /**
  398. * 判断路径是否为ftp目录
  399. * @param ftpPath
  400. * @return
  401. * @throws IOException
  402. */
  403. public boolean isDir(String ftpPath) throws IOException{
  404. if(ftpPath==null)
  405. return false;
  406. File f = new File(ftpPath);
  407. String lastName = f.getName();
  408. String parentDir = f.getParent();
  409. // 根目录没有上层目录
  410. if(parentDir==null)
  411. return true;
  412. FTPFile[] ftpFiles = ftpClient.listFiles(parentDir);
  413. for (int j=0; j<ftpFiles.length; j++) {
  414. FTPFile ftpFile = ftpFiles[j];
  415. if(ftpFile.isDirectory()==true && lastName.equals(ftpFile.getName())){
  416. return true;
  417. }
  418. }
  419. return false;
  420. }
  421. public boolean isDirB(String ftpPath) {
  422. String cwd = "/";
  423. try {
  424. cwd = ftpClient.printWorkingDirectory();
  425. } catch (IOException e) {
  426. LogHelper.logger.warn("",e);
  427. }
  428. try {
  429. boolean isDir = ftpClient.changeWorkingDirectory(ftpPath);
  430. ftpClient.changeWorkingDirectory(cwd);
  431. return isDir;
  432. }catch (IOException e) {}
  433. return false;
  434. }
  435.  
  436. /**
  437. * 返回指定目录文件列表(包括子目录)
  438. * @param ftpPath: ftp文件夹目录, 不能传文件
  439. * @return
  440. * @throws Exception
  441. */
  442. public List<String> listFtpFiles(String ftpPath) throws Exception{
  443. List<String> list = new ArrayList<String>();
  444. FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath);
  445. for (int j=0; j<ftpFiles.length; j++) {
  446. FTPFile ftpFile = ftpFiles[j];
  447. String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName());
  448. if(ftpFile.isFile()==true){
  449. list.add(subFtpPath);
  450. }
  451. else{
  452. List<String> subList = listFtpFiles(subFtpPath);
  453. list.addAll(subList);
  454. }
  455. }
  456. return list;
  457. }
  458. /**
  459. * 返回当前目录文件列表
  460. * @param ftpPath
  461. * @return
  462. * @throws IOException
  463. */
  464. public FTPFile[] listFiles(String ftpPath) throws IOException{
  465. return ftpClient.listFiles(ftpPath);
  466. }
  467. /**
  468. * ftp修改文件名
  469. * @param from
  470. * @param to
  471. * @return
  472. */
  473. public boolean rename(String from, String to){
  474. boolean bl = false;
  475. try {
  476. bl = ftpClient.rename(from, to);
  477. } catch (IOException e) {
  478. LogHelper.logger.warn("",e);
  479. }
  480. return bl;
  481. }
  482. /**
  483. * 删除文件
  484. * @param ftpPath
  485. * @return
  486. */
  487. public boolean deleteFile(String ftpPath){
  488. boolean bl = false;
  489. try {
  490. bl = ftpClient.deleteFile(ftpPath);
  491. } catch (IOException e) {
  492. LogHelper.logger.warn("",e);
  493. }
  494. return bl;
  495. }
  496.  
  497. public void test() throws Exception{
  498. //down("/tt/ss/msgutil.zip.tmp", "/root/Desktop/tmp/", true);
  499. down("/tt", "/root/Desktop/tmp/", false);
  500. ftpClient.rename("from", "to");
  501. FTPFile[] files = ftpClient.listFiles("");
  502. for(FTPFile ff : files){
  503. System.out.println(ff.getName());
  504. System.out.println(ff.getLink());
  505. }
  506. System.out.println(files);
  507. }
  508.  
  509. // test
  510. public static void main(String[] args) throws Exception {
  511.  
  512. //FtpHelper fh = new FtpHelper("192.169.126.100",21,"yfsb","inet-eyed20");
  513. FtpHelper fh = new FtpHelper();
  514. boolean bl = fh.connect("172.16.9.101",21,"test1","111");
  515. System.out.println("connect: "+bl);
  516.  
  517. List<String> list = fh.listFtpFiles("/");
  518. fh.uploadFile("C:/Users/wang/Desktop/testftp/tiedel.zip", "/tiedel.zip.tmp");
  519. fh.deleteFile("/tiedel.zip");
  520. bl = fh.rename("/tiedel.zip.tmp", "/tiedel.zip");
  521. bl = fh.isFile("/33");
  522. bl = fh.isDir("/tiedel.zip");
  523. //fh.down("/p1/fp", "C:/Users/wang/Desktop/testftp22/tmp", false);
  524. //fh.test();
  525. //bl = fh.createDir("/p1/p2/p3/p4/p5");
  526. //fh.upload("/root/Desktop/friendxml0.txt");
  527. //fh.upload("/root/Desktop/123", "/tt/ss2/");
  528. System.out.println(bl);
  529. }
  530.  
  531. }

Ftp上传文件的更多相关文章

  1. .net FTP上传文件

    FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...

  2. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  3. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  4. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  5. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

  6. FTP 上传文件

    有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...

  7. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

  8. C# FTP上传文件至服务器代码

    C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...

  9. Java ftp上传文件方法效率对比

    Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...

随机推荐

  1. SpringMVC一些功能

    1.日期格式转换 当页面提交日期格式时 默认的格式为2017/10/1 如果指定日期格式为2017-10-1 //初始化绑定日期格式--不定义初始化格式时只能默认用yyyy/MM/dd格式 @Init ...

  2. avaScript技术面试时要小心的三个问题

    JavaScript是所有现代浏览器的官方语言.同样的,JavaScript面试题出现在各种各样的面试中. 这篇文章不是讲述JavaScript最新的库.日常的开发实践,或是ES6的新功能.当然了,上 ...

  3. Bootstrap 实现CRUD示例及代码

    https://github.com/wenzhixin/bootstrap-table-examples/blob/master/crud/index.html <!DOCTYPE html& ...

  4. [thinkphp] 隐藏后台地址

    转自 http://document.thinkphp.cn/manual_3_2.html#module_deploy 如果不希望用户直接访问某个模块,可以设置模块映射(对后台的保护会比较实用). ...

  5. java 中整数类型的进制转换

    int a=10; Integer.toBinaryString(a); //转换成2进制Integer.toOctalString(a);  //转换成8进制Integer.toHexString( ...

  6. Java实现蛇形矩阵

    public class Solution { //下x++ 左y-- 上x-- 右y++ public void prints(int n) { int[][] mp = new int[n][n] ...

  7. 洛谷——P1869 愚蠢的组合数

    P1869 愚蠢的组合数 题目描述 最近老师教了狗狗怎么算组合数,狗狗又想到了一个问题... 狗狗定义C(N,K)表示从N个元素中不重复地选取K个元素的方案数. 狗狗想知道的是C(N,K)的奇偶性. ...

  8. [BZOJ3990][SDOI2015]排序(DFS)

    3990: [SDOI2015]排序 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 902  Solved: 463[Submit][Status][ ...

  9. BZOJ 4059 [Cerc2012]Non-boring sequences(启发式分治)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4059 [题目大意] 一个序列被称为是不无聊的,仅当它的每个连续子序列存在一个独一无二的 ...

  10. 【贪心】【后缀自动机】XIII Open Championship of Y.Kupala Grodno SU Grodno, Saturday, April 29, 2017 Problem E. Enter the Word

    题意:给你一个串,让你从左到右构造这个串,一次操作可以直接在当前串后面添加一个任意字符,或者拷贝当前串的任意一个子串到当前串的后面.问你最少要多少次操作才能构造出这个串. 从前向后贪心,从当前已构造的 ...