---
title: "java ftp"
author: "baggioback"
date: "2013-06-24T11:05:18Z"
tags: []
categories: ["企业架构"]
slug: "java-ftp"
draft: false
lastmod: "2013-06-24T11:05:18Z"
id: 1893245
url: "https://baggioback.iteye.com/blog/1893245"
---

在项目中使用到FTP功能,于是采用类似Spring的各种回调机制公用各种代码,减少代码的开发量,简化开发人员的学习难度.本文仅供学习交流使用,如有比较好的意见希望可以一起交流,再次表示感谢.

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

01. package easyway.tbs.transfer.ftp;
02. import java.io.IOException;
03. import org.apache.commons.net.ftp.FTPClient;
04. /\**
05. * FTPCLient回调
06. * @author longgangabai
07. \*
08. * @param &lt;T&gt;
09. \*/
10. public interface FTPClientCallback&lt;T&gt; {
11. public T doTransfer(FTPClient ftp)throws IOException;
12. }

 

 

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

01. package easyway.tbs.transfer.ftp;
02. import java.io.IOException;
03. import java.util.Collection;
04. import org.apache.commons.net.ftp.FTPFile;
05. /\**
06. * FTP操作的客户端操作上传下载
07. * @author longgangbai
08. \*
09. \*/
10. public interface FTPClientOperations {
11. /\**
12. * 文件上传的方法
13. * @param remote
14. * @param local
15. * @return
16. * @throws IOException
17. \*/
18. public UploadStatus upload(String remote, String local) throws IOException;
19. /\**
20. \*
21. * 从远程服务器目录下载文件到本地服务器目录中
22. * @param localdir FTP服务器保存目录
23. * @param remotedir FTP下载服务器目录
24. * @param localTempFile临时下载记录文件
25. * @return 成功返回true，否则返回false
26. \*/
27. public Collection&lt;String&gt; downloadList(final String localdir, final String remotedir,final String localTmpFile) throws IOException;
28. /\**
29. * 文件下载的方法
30. * @param remote
31. * @param local
32. * @return
33. * @throws IOException
34. \*/
35. public DownloadStatus downloadFile( String local,String remote) throws IOException;
36. /\**
37. * 查看服务器上文件列表方法
38. * @param remotedir
39. * @return
40. * @throws IOException
41. \*/
42. public FTPFile\[] list(final String remotedir) throws IOException;
43. }

 

 

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

001. package easyway.tbs.transfer.ftp;
002. import java.io.File;
003. import java.io.IOException;
004. import java.net.ConnectException;
005. import java.util.ArrayList;
006. import java.util.Collection;
007. import java.util.Properties;
008. import org.apache.commons.collections.CollectionUtils;
009. import org.apache.commons.lang.ArrayUtils;
010. import org.apache.commons.lang.StringUtils;
011. import org.apache.commons.lang.math.NumberUtils;
012. import org.apache.commons.net.ftp.FTPClient;
013. import org.apache.commons.net.ftp.FTPClientConfig;
014. import org.apache.commons.net.ftp.FTPFile;
015. import org.apache.commons.net.ftp.FTPReply;
016. import org.apache.log4j.Logger;
017. import easyway.tbs.commons.FileOperateUtils;
018. /\**
019. * Ftp回调模板
020. \*
021. * @author longgangbai
022. \*
023. \*/
024. public class FTPClientTemplate implements FTPClientOperations{
025. private static final Logger logger = Logger.getLogger(FTPClientTemplate.class);
026. private static String DEAFULT\_REMOTE\_CHARSET="UTF-8";
027. private static int DEAFULT\_REMOTE\_PORT=21;
028. private static String separator = File.separator;
029. private FTPClientConfig ftpClientConfig;
030. private String host;
031. private String username;
032. private String password;
033. private String port;
034. public FTPClientTemplate(String host,String user,String pwd,String port){
035. this.host=host;
036. this.username=user;
037. this.password=pwd;
038. this.port=port;
039. }
040. /\**
041. * 查看服务器上文件列表方法
042. * @param remotedir
043. * @return
044. * @throws IOException
045. \*/
046. public FTPFile\[] list(final String remotedir) throws IOException{
047. return   execute(new FTPClientCallback&lt;FTPFile\[]&gt;(){
048. public FTPFile\[] doTransfer(FTPClient ftp) throws IOException {
049. ftp.changeWorkingDirectory(remotedir);
050. FTPFile\[] files= ftp.listFiles(remotedir);
051. return files;
052. }
053. });
054. }
055. /\**
056. * 文件上传的方法
057. * @param remote
058. * @param local
059. * @return
060. * @throws IOException
061. \*/
062. public UploadStatus upload(final String local,final  String remote) throws IOException{
063. return   execute(new FTPClientCallback&lt;UploadStatus&gt;(){
064. public UploadStatus doTransfer(FTPClient ftpClient)throws IOException {
065. return FtpHelper.getInstance().upload(ftpClient, local, remote);
066. }
067. });
068. }
069. /\**
070. * 上传文件到服务器,新上传和断点续传
071. * @param remoteFile  远程文件名，在上传之前已经将服务器工作目录做了改变
072. * @param localFile   本地文件File句柄，绝对路径
073. * @param processStep  需要显示的处理进度步进值
074. * @param ftpClient  FTPClient引用
075. * @return
076. * @throws IOException
077. \*/
078. public UploadStatus uploadFile(String remoteFile, File localFile,
079. FTPClient ftpClient, long remoteSize) throws IOException {
080. return FtpHelper.getInstance().uploadFile(remoteFile, localFile, ftpClient, remoteSize);
081. }
082. /\**
083. * 从远程服务器目录下载文件到本地服务器目录中
084. * @param localdir FTP服务器保存目录
085. * @param remotedir FTP下载服务器目录
086. * @param localTempFile临时下载记录文件
087. * @return  成功下载记录
088. \*/
089. public Collection&lt;String&gt; downloadList(final String localdir, final String remotedir,final String localTmpFile) throws IOException {
090. return execute(new FTPClientCallback&lt;Collection&lt;String&gt;&gt;(){
091. public Collection&lt;String&gt; doTransfer(final FTPClient ftp) throws IOException {
092. //切换到下载目录的中
093. ftp.changeWorkingDirectory(remotedir);
094. //获取目录中所有的文件信息
095. FTPFile\[] ftpfiles=ftp.listFiles();
096. Collection&lt;String&gt; fileNamesCol=new ArrayList&lt;String&gt;();
097. //判断文件目录是否为空
098. if(!ArrayUtils.isEmpty(ftpfiles)){
099. for (FTPFile ftpfile : ftpfiles) {
100. String remoteFilePath=remotedir+separator+ftpfile.getName();
101. String localFilePath=localdir+separator+ftpfile.getName();
102. System.out.println("remoteFilePath ="+remoteFilePath +" localFilePath="+localFilePath);
103. //单个文件下载状态
104. DownloadStatus downStatus=downloadFile(remoteFilePath, localFilePath);
105. if(downStatus==DownloadStatus.Download\_New\_Success){
106. //临时目录中添加记录信息
107. fileNamesCol.add(remoteFilePath);
108. }
109. }
110. }
111. if(CollectionUtils.isNotEmpty(fileNamesCol)){
112. FileOperateUtils.writeLinesToFile(fileNamesCol, localTmpFile);
113. }
114. return  fileNamesCol;
115. }
116. });
117. }
118. /\**
119. * 从FTP服务器上下载文件,支持断点续传，上传百分比汇报
120. * @param remote  远程文件路径
121. * @param local 本地文件路径
122. * @return 上传的状态
123. * @throws IOException
124. \*
125. \*/
126. public DownloadStatus downloadFile(final String remote, final String local) throws IOException{
127. return   execute(new FTPClientCallback&lt;DownloadStatus&gt;(){
128. public DownloadStatus doTransfer(FTPClient ftpClient) throws IOException {
129. DownloadStatus result=FtpHelper.getInstance().download(ftpClient, remote, local);
130. return result;
131. }
132. });
133. }
134. /\**
135. * 执行FTP回调操作的方法
136. * @param callback   回调的函数
137. * @throws IOException
138. \*/
139. public &lt;T&gt; T  execute(FTPClientCallback&lt;T&gt; callback) throws IOException{
140. FTPClient ftp=new FTPClient();
141. try {
142. /\*if(getFtpClientConfig()!=null){
143. ftp.configure(getFtpClientConfig());
144. ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
145. }\*/
146. //登录FTP服务器
147. try {
148. //设置超时时间
149. ftp.setDataTimeout(7200);
150. //设置默认编码
151. ftp.setControlEncoding(DEAFULT\_REMOTE\_CHARSET);
152. //设置默认端口
153. ftp.setDefaultPort(DEAFULT\_REMOTE\_PORT);
154. //设置是否显示隐藏文件
155. ftp.setListHiddenFiles(false);
156. //连接ftp服务器
157. if(StringUtils.isNotEmpty(port)&&NumberUtils.isDigits(port)){
158. ftp.connect(host, Integer.valueOf(port));
159. }else{
160. ftp.connect(host);
161. }
162. } catch(ConnectException e) {
163. logger.error("连接FTP服务器失败："+ftp.getReplyString()+ftp.getReplyCode());
164. throw new IOException("Problem connecting the FTP-server fail",e);
165. }
166. //得到连接的返回编码
167. int reply=ftp.getReplyCode();
168. if(!FTPReply.isPositiveCompletion(reply)){
169. ftp.disconnect();
170. }
171. //登录失败权限验证失败
172. if(!ftp.login(getUsername(), getPassword())) {
173. ftp.quit();
174. ftp.disconnect();
175. logger.error("连接FTP服务器用户或者密码失败：："+ftp.getReplyString());
176. throw new IOException("Cant Authentificate to FTP-Server");
177. }
178. if(logger.isDebugEnabled()){
179. logger.info("成功登录FTP服务器："+host+" 端口："+port);
180. }
181. ftp.setFileType(FTPClient.BINARY\_FILE\_TYPE);
182. //回调FTP的操作
183. return callback.doTransfer(ftp);
184. }finally{
185. //FTP退出
186. ftp.logout();
187. //断开FTP连接
188. if(ftp.isConnected()){
189. ftp.disconnect();
190. }
191. }
192. }
193. protected String resolveFile(String file)
194. {
195. return null;
196. //return file.replace(System.getProperty("file.separator").charAt(0), this.remoteFileSep.charAt(0));
197. }
198. /\**
199. * 获取FTP的配置操作系统
200. * @return
201. \*/
202. public FTPClientConfig getFtpClientConfig() {
203. //获得系统属性集
204. Properties props=System.getProperties();
205. //操作系统名称
206. String osname=props.getProperty("os.name");
207. //针对window系统
208. if(osname.equalsIgnoreCase("Windows XP")){
209. ftpClientConfig=new FTPClientConfig(FTPClientConfig.SYST\_NT);
210. //针对linux系统
211. }else if(osname.equalsIgnoreCase("Linux")){
212. ftpClientConfig=new FTPClientConfig(FTPClientConfig.SYST\_UNIX);
213. }
214. if(logger.isDebugEnabled()){
215. logger.info("the ftp client system os Name "+osname);
216. }
217. return ftpClientConfig;
218. }
219. public String getHost() {
220. return host;
221. }
222. public void setHost(String host) {
223. this.host = host;
224. }
225. public String getPassword() {
226. return password;
227. }
228. public void setPassword(String password) {
229. this.password = password;
230. }
231. public String getUsername() {
232. return username;
233. }
234. public void setUsername(String username) {
235. this.username = username;
236. }
237. }

 

 

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

001. package easyway.tbs.transfer.ftp;
002. import java.io.File;
003. import java.io.FileOutputStream;
004. import java.io.IOException;
005. import java.io.InputStream;
006. import java.io.OutputStream;
007. import java.io.RandomAccessFile;
008. import java.util.StringTokenizer;
009. import org.apache.commons.net.ftp.FTP;
010. import org.apache.commons.net.ftp.FTPClient;
011. import org.apache.commons.net.ftp.FTPFile;
012. import org.apache.commons.net.ftp.FTPReply;
013. /\**
014. * FTP下载工具类
015. * @author longgangbai
016. \*
017. \*/
018. public class FtpHelper {
019. private static String DEAFULT\_REMOTE\_CHARSET="GBK";
020. private static String DEAFULT\_LOCAL\_CHARSET="iso-8859-1";
021. private static FtpHelper instance=new FtpHelper();
022. public static FtpHelper getInstance(){
023. return instance;
024. }
025. /\**
026. * 连接到FTP服务器
027. * @param hostname主机名
028. * @param port 端口
029. * @param username 用户名
030. * @param password 密码
031. * @return 是否连接成功
032. * @throws IOException
033. \*/
034. public  boolean connect(FTPClient ftpClient,String hostname, int port, String username,String password) throws IOException {
035. ftpClient.connect(hostname, port);
036. ftpClient.setControlEncoding(DEAFULT\_REMOTE\_CHARSET);
037. if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
038. if (ftpClient.login(username, password)) {
039. return true;
040. }
041. }
042. disconnect(ftpClient);
043. return false;
044. }
045. /\**
046. * 从FTP服务器上下载文件,支持断点续传，上传百分比汇报
047. * @param remoteFilePath  远程文件路径
048. * @param localFilePath 本地文件路径
049. * @return 上传的状态
050. * @throws IOException
051. \*/
052. public DownloadStatus download(FTPClient ftpClient,String remoteFilePath, String localFilePath)
053. throws IOException {
054. // 设置被动模式
055. ftpClient.enterLocalPassiveMode();
056. // 设置以二进制方式传输
057. ftpClient.setFileType(FTP.BINARY\_FILE\_TYPE);
058. DownloadStatus result;
059. // 检查远程文件是否存在
060. FTPFile\[] files = ftpClient.listFiles(new String(
061. remoteFilePath.getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET));
062. if (files.length != 1) {
063. System.out.println("远程文件不存在");
064. return DownloadStatus.Remote\_File\_Noexist;
065. }
066. long lRemoteSize = files\[0].getSize();
067. File f = new File(localFilePath);
068. // 本地存在文件，进行断点下载
069. if (f.exists()) {
070. long localSize = f.length();
071. // 判断本地文件大小是否大于远程文件大小
072. if (localSize &gt;= lRemoteSize) {
073. System.out.println("本地文件大于远程文件，下载中止");
074. return DownloadStatus.Local\_Bigger\_Remote;
075. }
076. // 进行断点续传，并记录状态
077. FileOutputStream out = new FileOutputStream(f, true);
078. ftpClient.setRestartOffset(localSize);
079. InputStream in = ftpClient.retrieveFileStream(new String(remoteFilePath
080. .getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET));
081. byte\[] bytes = new byte\[1024];
082. long step = lRemoteSize / 100;
083. long process = localSize / step;
084. int c;
085. while ((c = in.read(bytes)) != -1) {
086. out.write(bytes, 0, c);
087. localSize += c;
088. long nowProcess = localSize / step;
089. if (nowProcess &gt; process) {
090. process = nowProcess;
091. if (process % 10 == 0){
092. System.out.println("下载进度：" + process);
093. }
094. // TODO 更新文件下载进度,值存放在process变量中
095. }
096. }
097. in.close();
098. out.close();
099. boolean isDo = ftpClient.completePendingCommand();
100. if (isDo) {
101. result = DownloadStatus.Download\_From\_Break\_Success;
102. } else {
103. result = DownloadStatus.Download\_From\_Break\_Failed;
104. }
105. } else {
106. OutputStream out = new FileOutputStream(f);
107. InputStream in = ftpClient.retrieveFileStream(new String(remoteFilePath
108. .getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET));
109. byte\[] bytes = new byte\[1024];
110. long step = lRemoteSize / 100;
111. long process = 0;
112. long localSize = 0L;
113. int c;
114. while ((c = in.read(bytes)) != -1) {
115. out.write(bytes, 0, c);
116. localSize += c;
117. long nowProcess = localSize / step;
118. if (nowProcess &gt; process) {
119. process = nowProcess;
120. if (process % 10 == 0){
121. System.out.println("下载进度：" + process);
122. }
123. // TODO 更新文件下载进度,值存放在process变量中
124. }
125. }
126. in.close();
127. out.close();
128. boolean upNewStatus = ftpClient.completePendingCommand();
129. if (upNewStatus) {
130. result = DownloadStatus.Download\_New\_Success;
131. } else {
132. result = DownloadStatus.Download\_New\_Failed;
133. }
134. }
135. return result;
136. }
137. /\**
138. \*
139. * 上传文件到FTP服务器，支持断点续传
140. * @param localFilePath  本地文件名称，绝对路径
141. * @param remoteFilePath   远程文件路径，使用/home/directory1/subdirectory/file.ext
142. * 按照Linux上的路径指定方式，支持多级目录嵌套，支持递归创建不存在的目录结构
143. * @return 上传结果
144. * @throws IOException
145. \*/
146. public UploadStatus upload(FTPClient ftpClient,String localFilePath, String remoteFilePath) throws IOException {
147. // 设置PassiveMode传输
148. ftpClient.enterLocalPassiveMode();
149. // 设置以二进制流的方式传输
150. ftpClient.setFileType(FTP.BINARY\_FILE\_TYPE);
151. ftpClient.setControlEncoding(DEAFULT\_REMOTE\_CHARSET);
152. UploadStatus result;
153. // 对远程目录的处理
154. String remoteFileName = remoteFilePath;
155. if (remoteFilePath.contains("/")) {
156. remoteFileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
157. // 创建服务器远程目录结构，创建失败直接返回
158. if (createDirecroty(remoteFilePath, ftpClient) == UploadStatus.Create\_Directory\_Fail) {
159. return UploadStatus.Create\_Directory\_Fail;
160. }
161. }
162. // ftpClient.feat();
163. // System.out.println( ftpClient.getReply());
164. // System.out.println( ftpClient.acct(null));
165. // System.out.println(ftpClient.getReplyCode());
166. // System.out.println(ftpClient.getReplyString());
167. // 检查远程是否存在文件
168. FTPFile\[] files = ftpClient.listFiles(new String(remoteFileName
169. .getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET));
170. if (files.length == 1) {
171. long remoteSize = files\[0].getSize();
172. File f = new File(localFilePath);
173. long localSize = f.length();
174. if (remoteSize == localSize) { // 文件存在
175. return UploadStatus.File\_Exits;
176. } else if (remoteSize &gt; localSize) {
177. return UploadStatus.Remote\_Bigger\_Local;
178. }
179. // 尝试移动文件内读取指针,实现断点续传
180. result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
181. // 如果断点续传没有成功，则删除服务器上文件，重新上传
182. if (result == UploadStatus.Upload\_From\_Break\_Failed) {
183. if (!ftpClient.deleteFile(remoteFileName)) {
184. return UploadStatus.Delete\_Remote\_Faild;
185. }
186. result = uploadFile(remoteFileName, f, ftpClient, 0);
187. }
188. } else {
189. result = uploadFile(remoteFileName, new File(localFilePath), ftpClient, 0);
190. }
191. return result;
192. }
193. /\**
194. \*
195. * 断开与远程服务器的连接
196. * @throws IOException
197. \*/
198. public void disconnect(FTPClient ftpClient) throws IOException {
199. if (ftpClient.isConnected()) {
200. ftpClient.disconnect();
201. }
202. }
203. /\**
204. * 递归创建远程服务器目录
205. * @param remote 远程服务器文件绝对路径
206. * @param ftpClient  FTPClient对象
207. * @return 目录创建是否成功
208. * @throws IOException
209. \*/
210. public UploadStatus createDirecroty(String remote, FTPClient ftpClient)
211. throws IOException {
212. UploadStatus status = UploadStatus.Create\_Directory\_Success;
213. String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
214. if (!directory.equalsIgnoreCase("/")
215. && !ftpClient.changeWorkingDirectory(new String(directory
216. .getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET))) {
217. // 如果远程目录不存在，则递归创建远程服务器目录
218. int start = 0;
219. int end = 0;
220. if (directory.startsWith("/")) {
221. start = 1;
222. } else {
223. start = 0;
224. }
225. end = directory.indexOf("/", start);
226. while (true) {
227. String subDirectory = new String(remote.substring(start, end)
228. .getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET);
229. if (!ftpClient.changeWorkingDirectory(subDirectory)) {
230. if (ftpClient.makeDirectory(subDirectory)) {
231. ftpClient.changeWorkingDirectory(subDirectory);
232. } else {
233. System.out.println("创建目录失败");
234. return UploadStatus.Create\_Directory\_Fail;
235. }
236. }
237. start = end + 1;
238. end = directory.indexOf("/", start);
239. // 检查所有目录是否创建完毕
240. if (end &lt;= start) {
241. break;
242. }
243. }
244. }
245. return status;
246. }
247. /\**
248. * 上传文件到服务器,新上传和断点续传
249. * @param remoteFile  远程文件名，在上传之前已经将服务器工作目录做了改变
250. * @param localFile   本地文件File句柄，绝对路径
251. * @param processStep  需要显示的处理进度步进值
252. * @param ftpClient  FTPClient引用
253. * @return
254. * @throws IOException
255. \*/
256. public UploadStatus uploadFile(String remoteFile, File localFile,
257. FTPClient ftpClient, long remoteSize) throws IOException {
258. UploadStatus status;
259. // 显示进度的上传
260. long step = localFile.length() / 100;
261. long process = 0;
262. long localreadbytes = 0L;
263. RandomAccessFile raf = new RandomAccessFile(localFile, "r");
264. String remote = new String(remoteFile.getBytes(DEAFULT\_REMOTE\_CHARSET), DEAFULT\_LOCAL\_CHARSET);
265. OutputStream out = ftpClient.appendFileStream(remote);
266. if (out == null)
267. {
268. String message = ftpClient.getReplyString();
269. throw new RuntimeException(message);
270. }
271. // 断点续传
272. if (remoteSize &gt; 0) {
273. ftpClient.setRestartOffset(remoteSize);
274. process = remoteSize / step;
275. raf.seek(remoteSize);
276. localreadbytes = remoteSize;
277. }
278. byte\[] bytes = new byte\[1024];
279. int c;
280. while ((c = raf.read(bytes)) != -1) {
281. out.write(bytes, 0, c);
282. localreadbytes += c;
283. if (localreadbytes / step != process) {
284. process = localreadbytes / step;
285. System.out.println("上传进度:" + process);
286. // TODO 汇报上传状态
287. }
288. }
289. out.flush();
290. raf.close();
291. out.close();
292. boolean result = ftpClient.completePendingCommand();
293. if (remoteSize &gt; 0) {
294. status = result ? UploadStatus.Upload\_From\_Break\_Success
295. : UploadStatus.Upload\_From\_Break\_Failed;
296. } else {
297. status = result ? UploadStatus.Upload\_New\_File\_Success
298. : UploadStatus.Upload\_New\_File\_Failed;
299. }
300. return status;
301. }
302. protected void makeRemoteDir(FTPClient ftp, String dir)
303. throws IOException
304. {
305. String workingDirectory = ftp.printWorkingDirectory();
306. if (dir.indexOf("/") == 0) {
307. ftp.changeWorkingDirectory("/");
308. }
309. String subdir = new String();
310. StringTokenizer st = new StringTokenizer(dir, "/");
311. while (st.hasMoreTokens()) {
312. subdir = st.nextToken();
313. if (!(ftp.changeWorkingDirectory(subdir))) {
314. if (!(ftp.makeDirectory(subdir)))
315. {
316. int rc = ftp.getReplyCode();
317. if (((rc != 550) && (rc != 553) && (rc != 521)))
318. {
319. throw new IOException("could not create directory: " + ftp.getReplyString());
320. }
321. }
322. else {
323. ftp.changeWorkingDirectory(subdir);
324. }
325. }
326. }
327. if (workingDirectory != null){
328. ftp.changeWorkingDirectory(workingDirectory);
329. }
330. }
331. /\**
332. * 获取指定目录下的文件名称列表
333. * @param currentDir
334. *            需要获取其子目录的当前目录名称
335. * @return 返回子目录字符串数组
336. \*/
337. public String\[] GetFileNames(FTPClient ftpClient,String currentDir) {
338. String\[] dirs = null;
339. try {
340. if (currentDir == null)
341. dirs = ftpClient.listNames();
342. else
343. dirs = ftpClient.listNames(currentDir);
344. } catch (IOException e) {
345. e.printStackTrace();
346. }
347. return dirs;
348. }
349. /\**
350. * 获取指定目录下的文件与目录信息集合
351. * @param currentDir
352. *            指定的当前目录
353. * @return 返回的文件集合
354. \*/
355. public FTPFile\[] GetDirAndFilesInfo(FTPClient ftpClient,String currentDir)
356. {
357. FTPFile\[] files = null;
358. try
359. {
360. if (currentDir == null)
361. files = ftpClient.listFiles();
362. else
363. files = ftpClient.listFiles(currentDir);
364. }
365. catch (IOException ex)
366. {
367. ex.printStackTrace();
368. }
369. return files;
370. }
371. }

 

 

 

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

01. package easyway.tbs.transfer.ftp;
02. import easyway.tbs.commons.EnumUtils;
03. /\**
04. * 文件下载状态
05. * @author longgangbai
06. \*
07. \*/
08. public enum DownloadStatus {
09. Remote\_File\_Noexist(0,"远程文件不存在"), // 远程文件不存在
10. //用于单个下载
11. Download\_New\_Success(1,"下载文件成功"), // 下载文件成功
12. Download\_New\_Failed(2,"下载文件失败"), // 下载文件失败
13. Local\_Bigger\_Remote(3,"本地文件大于远程文件"), // 本地文件大于远程文件
14. Download\_From\_Break\_Success(4,"文件断点续传成功"), // 断点续传成功
15. Download\_From\_Break\_Failed(5,"文件断点续传失败"), // 断点续传失败
16. //用于批量下载
17. Download\_Batch\_Success(6,"文件批量下载成功"),
18. Download\_Batch\_Failure(7,"文件批量下载失败"),
19. Download\_Batch\_Failure\_SUCCESS(8,"文件批量下载不完全成功");
20. private int code;
21. private String description;
22. private DownloadStatus(int code , String description) {
23. this.code = code;
24. this.description = description;
25. }
26. public int getCode() {
27. return code;
28. }
29. public void setCode(int code) {
30. this.code = code;
31. }
32. public String getDescription() {
33. return description;
34. }
35. public void setDescription(String description) {
36. this.description = description;
37. }
38. /\**
39. * 下载状态中中使用的code
40. * @param code
41. * @return
42. \*/
43. public static DownloadStatus fromCode(int code) {
44. return EnumUtils.fromEnumProperty(DownloadStatus.class, "code", code);
45. }
46. }

 

 

 

Java代码  [![收藏代码](http://topmanopensource.iteye.com/images/icon_star.png)]()

01. package easyway.tbs.transfer.ftp;
02. import easyway.tbs.commons.EnumUtils;
03. /\**
04. * 文件上传状态
05. * @author longgangbai
06. \*
07. \*/
08. public enum UploadStatus {
09. Create\_Directory\_Fail(0,"远程服务器相应目录创建失败"), // 远程服务器相应目录创建失败
10. Create\_Directory\_Success(1,"远程服务器闯将目录成功"), // 远程服务器闯将目录成功
11. Upload\_New\_File\_Success(2,"上传新文件成功"), // 上传新文件成功
12. Upload\_New\_File\_Failed(3,"上传新文件失败"), // 上传新文件失败
13. File\_Exits(4,"文件已经存在"), // 文件已经存在
14. Remote\_Bigger\_Local(5,"远程文件大于本地文件"), // 远程文件大于本地文件
15. Upload\_From\_Break\_Success(6," 断点续传成功"), // 断点续传成功
16. Upload\_From\_Break\_Failed(7,"断点续传失败"), // 断点续传失败
17. Delete\_Remote\_Faild(8,"删除远程文件失败"); // 删除远程文件失败
18. private int code;
19. private String description;
20. private UploadStatus(int code , String description) {
21. this.code = code;
22. this.description = description;
23. }
24. public int getCode() {
25. return code;
26. }
27. public void setCode(int code) {
28. this.code = code;
29. }
30. public String getDescription() {
31. return description;
32. }
33. public void setDescription(String description) {
34. this.description = description;
35. }
36. /\**
37. * 下载状态中中使用的code
38. * @param code
39. * @return
40. \*/
41. public static UploadStatus fromCode(int code) {
42. return EnumUtils.fromEnumProperty(UploadStatus.class, "code", code);
43. }
44. }