ITeye博客

java ftp

baggioback · 2013-06-24 11:05 · 技术 · 企业架构 · Markdown

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

Java代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import java.io.IOException;
  3. import org.apache.commons.net.ftp.FTPClient;
  4. /**
  5. * FTPCLient回调
  6. * @author longgangabai
  7. *
  8. * @param <T>
  9. */
  10. public interface FTPClientCallback<T> {
  11. public T doTransfer(FTPClient ftp)throws IOException;
  12. }

 

 

Java代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import java.io.IOException;
  3. import java.util.Collection;
  4. import org.apache.commons.net.ftp.FTPFile;
  5. /**
  6. * FTP操作的客户端操作上传下载
  7. * @author longgangbai
  8. *
  9. */
  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<String> 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代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.ConnectException;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.Properties;
  8. import org.apache.commons.collections.CollectionUtils;
  9. import org.apache.commons.lang.ArrayUtils;
  10. import org.apache.commons.lang.StringUtils;
  11. import org.apache.commons.lang.math.NumberUtils;
  12. import org.apache.commons.net.ftp.FTPClient;
  13. import org.apache.commons.net.ftp.FTPClientConfig;
  14. import org.apache.commons.net.ftp.FTPFile;
  15. import org.apache.commons.net.ftp.FTPReply;
  16. import org.apache.log4j.Logger;
  17. import easyway.tbs.commons.FileOperateUtils;
  18. /**
  19. * Ftp回调模板
  20. *
  21. * @author longgangbai
  22. *
  23. */
  24. public class FTPClientTemplate implements FTPClientOperations{
  25. private static final Logger logger = Logger.getLogger(FTPClientTemplate.class);
  26. private static String DEAFULT_REMOTE_CHARSET="UTF-8";
  27. private static int DEAFULT_REMOTE_PORT=21;
  28. private static String separator = File.separator;
  29. private FTPClientConfig ftpClientConfig;
  30. private String host;
  31. private String username;
  32. private String password;
  33. private String port;
  34. public FTPClientTemplate(String host,String user,String pwd,String port){
  35. this.host=host;
  36. this.username=user;
  37. this.password=pwd;
  38. this.port=port;
  39. }
  40. /**
  41. * 查看服务器上文件列表方法
  42. * @param remotedir
  43. * @return
  44. * @throws IOException
  45. */
  46. public FTPFile[] list(final String remotedir) throws IOException{
  47. return   execute(new FTPClientCallback<FTPFile[]>(){
  48. public FTPFile[] doTransfer(FTPClient ftp) throws IOException {
  49. ftp.changeWorkingDirectory(remotedir);
  50. FTPFile[] files= ftp.listFiles(remotedir);
  51. return files;
  52. }
  53. });
  54. }
  55. /**
  56. * 文件上传的方法
  57. * @param remote
  58. * @param local
  59. * @return
  60. * @throws IOException
  61. */
  62. public UploadStatus upload(final String local,final  String remote) throws IOException{
  63. return   execute(new FTPClientCallback<UploadStatus>(){
  64. public UploadStatus doTransfer(FTPClient ftpClient)throws IOException {
  65. return FtpHelper.getInstance().upload(ftpClient, local, remote);
  66. }
  67. });
  68. }
  69. /**
  70. * 上传文件到服务器,新上传和断点续传
  71. * @param remoteFile  远程文件名,在上传之前已经将服务器工作目录做了改变
  72. * @param localFile   本地文件File句柄,绝对路径
  73. * @param processStep  需要显示的处理进度步进值
  74. * @param ftpClient  FTPClient引用
  75. * @return
  76. * @throws IOException
  77. */
  78. public UploadStatus uploadFile(String remoteFile, File localFile,
  79. FTPClient ftpClient, long remoteSize) throws IOException {
  80. return FtpHelper.getInstance().uploadFile(remoteFile, localFile, ftpClient, remoteSize);
  81. }
  82. /**
  83. * 从远程服务器目录下载文件到本地服务器目录中
  84. * @param localdir FTP服务器保存目录
  85. * @param remotedir FTP下载服务器目录
  86. * @param localTempFile临时下载记录文件
  87. * @return  成功下载记录
  88. */
  89. public Collection<String> downloadList(final String localdir, final String remotedir,final String localTmpFile) throws IOException {
  90. return execute(new FTPClientCallback<Collection<String>>(){
  91. public Collection<String> doTransfer(final FTPClient ftp) throws IOException {
  92. //切换到下载目录的中
  93. ftp.changeWorkingDirectory(remotedir);
  94. //获取目录中所有的文件信息
  95. FTPFile[] ftpfiles=ftp.listFiles();
  96. Collection<String> fileNamesCol=new ArrayList<String>();
  97. //判断文件目录是否为空
  98. if(!ArrayUtils.isEmpty(ftpfiles)){
  99. 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<DownloadStatus>(){
  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 <T> T  execute(FTPClientCallback<T> 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代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.io.RandomAccessFile;
  8. import java.util.StringTokenizer;
  9. import org.apache.commons.net.ftp.FTP;
  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. /**
  14. * FTP下载工具类
  15. * @author longgangbai
  16. *
  17. */
  18. public class FtpHelper {
  19. private static String DEAFULT_REMOTE_CHARSET="GBK";
  20. private static String DEAFULT_LOCAL_CHARSET="iso-8859-1";
  21. private static FtpHelper instance=new FtpHelper();
  22. public static FtpHelper getInstance(){
  23. return instance;
  24. }
  25. /**
  26. * 连接到FTP服务器
  27. * @param hostname主机名
  28. * @param port 端口
  29. * @param username 用户名
  30. * @param password 密码
  31. * @return 是否连接成功
  32. * @throws IOException
  33. */
  34. public  boolean connect(FTPClient ftpClient,String hostname, int port, String username,String password) throws IOException {
  35. ftpClient.connect(hostname, port);
  36. ftpClient.setControlEncoding(DEAFULT_REMOTE_CHARSET);
  37. if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  38. if (ftpClient.login(username, password)) {
  39. return true;
  40. }
  41. }
  42. disconnect(ftpClient);
  43. return false;
  44. }
  45. /**
  46. * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报
  47. * @param remoteFilePath  远程文件路径
  48. * @param localFilePath 本地文件路径
  49. * @return 上传的状态
  50. * @throws IOException
  51. */
  52. public DownloadStatus download(FTPClient ftpClient,String remoteFilePath, String localFilePath)
  53. throws IOException {
  54. // 设置被动模式
  55. ftpClient.enterLocalPassiveMode();
  56. // 设置以二进制方式传输
  57. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  58. DownloadStatus result;
  59. // 检查远程文件是否存在
  60. FTPFile[] files = ftpClient.listFiles(new String(
  61. remoteFilePath.getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));
  62. if (files.length != 1) {
  63. System.out.println("远程文件不存在");
  64. return DownloadStatus.Remote_File_Noexist;
  65. }
  66. long lRemoteSize = files[0].getSize();
  67. File f = new File(localFilePath);
  68. // 本地存在文件,进行断点下载
  69. if (f.exists()) {
  70. long localSize = f.length();
  71. // 判断本地文件大小是否大于远程文件大小
  72. if (localSize >= lRemoteSize) {
  73. System.out.println("本地文件大于远程文件,下载中止");
  74. return DownloadStatus.Local_Bigger_Remote;
  75. }
  76. // 进行断点续传,并记录状态
  77. FileOutputStream out = new FileOutputStream(f, true);
  78. ftpClient.setRestartOffset(localSize);
  79. InputStream in = ftpClient.retrieveFileStream(new String(remoteFilePath
  80. .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));
  81. byte[] bytes = new byte[1024];
  82. long step = lRemoteSize / 100;
  83. long process = localSize / step;
  84. int c;
  85. while ((c = in.read(bytes)) != -1) {
  86. out.write(bytes, 0, c);
  87. localSize += c;
  88. long nowProcess = localSize / step;
  89. if (nowProcess > process) {
  90. process = nowProcess;
  91. if (process % 10 == 0){
  92. System.out.println("下载进度:" + process);
  93. }
  94. // TODO 更新文件下载进度,值存放在process变量中
  95. }
  96. }
  97. in.close();
  98. out.close();
  99. 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 > 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 > 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 <= 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 > 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 > 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代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import easyway.tbs.commons.EnumUtils;
  3. /**
  4. * 文件下载状态
  5. * @author longgangbai
  6. *
  7. */
  8. public enum DownloadStatus {
  9. 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代码  收藏代码

  1. package easyway.tbs.transfer.ftp;
  2. import easyway.tbs.commons.EnumUtils;
  3. /**
  4. * 文件上传状态
  5. * @author longgangbai
  6. *
  7. */
  8. public enum UploadStatus {
  9. 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。