apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出

用到了apache 的 commons-net-3.0.1.jar 和 log4j-1.2.15.jar 这连个jar包

JAVA 代码如下:

  1 package com.bjut.edu.cn.ftp;
  2
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileNotFoundException;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.util.TimeZone;
 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
 16 import org.apache.log4j.Logger;
 17
 18 public class Ftp {
 19     private FTPClient ftpClient;
 20     private String strIp;
 21     private int intPort;
 22     private String user;
 23     private String password;
 24
 25     private static Logger logger = Logger.getLogger(Ftp.class.getName());
 26
 27     /* *
 28      * Ftp构造函数
 29      */
 30     public Ftp(String strIp, int intPort, String user, String Password) {
 31         this.strIp = strIp;
 32         this.intPort = intPort;
 33         this.user = user;
 34         this.password = Password;
 35         this.ftpClient = new FTPClient();
 36     }
 37     /**
 38      * @return 判断是否登入成功
 39      * */
 40     public boolean ftpLogin() {
 41         boolean isLogin = false;
 42         FTPClientConfig ftpClientConfig = new FTPClientConfig();
 43         ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
 44         this.ftpClient.setControlEncoding("GBK");
 45         this.ftpClient.configure(ftpClientConfig);
 46         try {
 47             if (this.intPort > 0) {
 48                 this.ftpClient.connect(this.strIp, this.intPort);
 49             } else {
 50                 this.ftpClient.connect(this.strIp);
 51             }
 52             // FTP服务器连接回答
 53             int reply = this.ftpClient.getReplyCode();
 54             if (!FTPReply.isPositiveCompletion(reply)) {
 55                 this.ftpClient.disconnect();
 56                 logger.error("登录FTP服务失败!");
 57                 return isLogin;
 58             }
 59             this.ftpClient.login(this.user, this.password);
 60             // 设置传输协议
 61             this.ftpClient.enterLocalPassiveMode();
 62             this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
 63             logger.info("恭喜" + this.user + "成功登陆FTP服务器");
 64             isLogin = true;
 65         } catch (Exception e) {
 66             e.printStackTrace();
 67             logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
 68         }
 69         this.ftpClient.setBufferSize(1024 * 2);
 70         this.ftpClient.setDataTimeout(30 * 1000);
 71         return isLogin;
 72     }
 73
 74     /**
 75      * @退出关闭服务器链接
 76      * */
 77     public void ftpLogOut() {
 78         if (null != this.ftpClient && this.ftpClient.isConnected()) {
 79             try {
 80                 boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
 81                 if (reuslt) {
 82                     logger.info("成功退出服务器");
 83                 }
 84             } catch (IOException e) {
 85                 e.printStackTrace();
 86                 logger.warn("退出FTP服务器异常!" + e.getMessage());
 87             } finally {
 88                 try {
 89                     this.ftpClient.disconnect();// 关闭FTP服务器的连接
 90                 } catch (IOException e) {
 91                     e.printStackTrace();
 92                     logger.warn("关闭FTP服务器的连接异常!");
 93                 }
 94             }
 95         }
 96     }
 97
 98     /***
 99      * 上传Ftp文件
100      * @param localFile 当地文件
101      * @param romotUpLoadePath上传服务器路径 - 应该以/结束
102      * */
103     public boolean uploadFile(File localFile, String romotUpLoadePath) {
104         BufferedInputStream inStream = null;
105         boolean success = false;
106         try {
107             this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
108             inStream = new BufferedInputStream(new FileInputStream(localFile));
109             logger.info(localFile.getName() + "开始上传.....");
110             success = this.ftpClient.storeFile(localFile.getName(), inStream);
111             if (success == true) {
112                 logger.info(localFile.getName() + "上传成功");
113                 return success;
114             }
115         } catch (FileNotFoundException e) {
116             e.printStackTrace();
117             logger.error(localFile + "未找到");
118         } catch (IOException e) {
119             e.printStackTrace();
120         } finally {
121             if (inStream != null) {
122                 try {
123                     inStream.close();
124                 } catch (IOException e) {
125                     e.printStackTrace();
126                 }
127             }
128         }
129         return success;
130     }
131
132     /***
133      * 下载文件
134      * @param remoteFileName   待下载文件名称
135      * @param localDires 下载到当地那个路径下
136      * @param remoteDownLoadPath remoteFileName所在的路径
137      * */
138
139     public boolean downloadFile(String remoteFileName, String localDires,
140             String remoteDownLoadPath) {
141         String strFilePath = localDires + remoteFileName;
142         BufferedOutputStream outStream = null;
143         boolean success = false;
144         try {
145             this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
146             outStream = new BufferedOutputStream(new FileOutputStream(
147                     strFilePath));
148             logger.info(remoteFileName + "开始下载....");
149             success = this.ftpClient.retrieveFile(remoteFileName, outStream);
150             if (success == true) {
151                 logger.info(remoteFileName + "成功下载到" + strFilePath);
152                 return success;
153             }
154         } catch (Exception e) {
155             e.printStackTrace();
156             logger.error(remoteFileName + "下载失败");
157         } finally {
158             if (null != outStream) {
159                 try {
160                     outStream.flush();
161                     outStream.close();
162                 } catch (IOException e) {
163                     e.printStackTrace();
164                 }
165             }
166         }
167         if (success == false) {
168             logger.error(remoteFileName + "下载失败!!!");
169         }
170         return success;
171     }
172
173     /***
174      * @上传文件夹
175      * @param localDirectory
176      *            当地文件夹
177      * @param remoteDirectoryPath
178      *            Ftp 服务器路径 以目录"/"结束
179      * */
180     public boolean uploadDirectory(String localDirectory,
181             String remoteDirectoryPath) {
182         File src = new File(localDirectory);
183         try {
184             remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
185             this.ftpClient.makeDirectory(remoteDirectoryPath);
186             // ftpClient.listDirectories();
187         } catch (IOException e) {
188             e.printStackTrace();
189             logger.info(remoteDirectoryPath + "目录创建失败");
190         }
191         File[] allFile = src.listFiles();
192         for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
193             if (!allFile[currentFile].isDirectory()) {
194                 String srcName = allFile[currentFile].getPath().toString();
195                 uploadFile(new File(srcName), remoteDirectoryPath);
196             }
197         }
198         for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
199             if (allFile[currentFile].isDirectory()) {
200                 // 递归
201                 uploadDirectory(allFile[currentFile].getPath().toString(),
202                         remoteDirectoryPath);
203             }
204         }
205         return true;
206     }
207
208     /***
209      * @下载文件夹
210      * @param localDirectoryPath本地地址
211      * @param remoteDirectory 远程文件夹
212      * */
213     public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
214         try {
215             String fileName = new File(remoteDirectory).getName();
216             localDirectoryPath = localDirectoryPath + fileName + "//";
217             new File(localDirectoryPath).mkdirs();
218             FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
219             for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
220                 if (!allFile[currentFile].isDirectory()) {
221                     downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
222                 }
223             }
224             for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
225                 if (allFile[currentFile].isDirectory()) {
226                     String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
227                     downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
228                 }
229             }
230         } catch (IOException e) {
231             e.printStackTrace();
232             logger.info("下载文件夹失败");
233             return false;
234         }
235         return true;
236     }
237     // FtpClient的Set 和 Get 函数
238     public FTPClient getFtpClient() {
239         return ftpClient;
240     }
241     public void setFtpClient(FTPClient ftpClient) {
242         this.ftpClient = ftpClient;
243     }
244
245     public static void main(String[] args) throws IOException {
246         Ftp ftp=new Ftp("10.3.15.1",21,"ghips","ghipsteam");
247         ftp.ftpLogin();
248         //上传文件夹
249         ftp.uploadDirectory("d://DataProtemp", "/home/data/");
250         //下载文件夹
251         ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
252         ftp.ftpLogOut();
253     }
254 }
时间: 2024-11-05 14:41:40

apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出的相关文章

ftp org.apache.commons.net.ftp.FTPClient 判断文件是否存在

String path = "/SJPT/ONPUT/HMD_TEST/" ; FtpTool.getFTPClient().changeWorkingDirectory(path); String reply = FtpTool.getFTPClient().getReplyString().substring(0, 3); if (reply.equals("250")) { System.out.println("We will now proces

putty对Linux上传下载文件或文件夹

putty是一个开源软件,目前为止最新版本为0.70.对于文件或文件夹的上传下载,在Windows下它提供了pscp和psftp两个命令. (1).pscp pscp在命令提示符中使用,只要putty(ssh)能够远程,就能使用该命令. pscp [Windows上的路径,可绝对可相对] [Linux用户]@[Linux的IP地址或网络内唯一主机名]:[Linux上存放地址,绝对路径] pscp [Linux用户]@[Linux的IP地址或网络内唯一主机名]:[Linux上存放地址,绝对路径]

FTP客户端上传下载实现

1.第一次感觉MS也有这么难用的MFC类: 2.CFtpFileFind类只能实例化一个,多个实例同时查找会出错(因此下载时不能递归): 3.本程序支持文件夹嵌套上传下载: 4.boost::filesystem::create_directory不能递归创建文件夹,需手动实现 代码如下: CFtpClient.h 1 #ifndef __ftp_client_h__ 2 #define __ftp_client_h__ 3 4 #include <afxinet.h> 5 #include

Java 利用Apache Commons Net 实现 FTP文件上传下载

package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Comparator;

apache FtpClient上传下载删除文件夹及文件

/* * 文件名:FtpUtil.java * 描述:FTP操作 * 修改时间2014-08-10 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import jav

基于commons-net实现ftp创建文件夹、上传、下载功能

原文:http://www.open-open.com/code/view/1420774470187 package com.demo.ftp; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter

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

FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”.用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件.在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)."下载"文件就是从远程主机拷贝文件至自己的计算机上:&quo

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

Java实现FTP文件与文件夹的上传和下载 http://www.cnblogs.com/winorgohome/archive/2016/11/22/6088013.html FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”.用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件.在FTP的使用当中,用户经常遇

【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

和上一份简单 上传下载一样 来,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html API拿走不谢!!! 1.FTP配置实体 1 package com.agen.util; 2 3 public class FtpConfig { 4 //主机ip 5 private String FtpHost = "192.168.18.252&quo