使用Apache Commons Net包实现javaFTP来上传目录

简介:
使用Apache Commons Net包实现javaFTP来上传目录
 
复杂的地方体现在文件夹的上传。
 
在前面层用Apache Commons Net工具包实现了Java FTP单个文件的上传下载功能,这次,实现的是对一个本地目录的上传,实现费了很大劲,虽然实现了 ,但是感觉还是对此封装不是非常满意,改用了其他的FTP客户端工具。将这个半成品放出来供各位研究吧。
 
ftpconfig.properties
username=admin 
password=123 
ip=192.168.14.117 
port=21
 
package comftp; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPClientConfig; 
import org.apache.commons.net.ftp.FTPReply; 

import java.io.*; 
import java.net.SocketException; 
import java.text.SimpleDateFormat; 
import java.util.Properties; 

/** 
* Created by IntelliJ IDEA. 

* @author leizhimin 2008-9-12 10:32:39 
*/
 
public  class FtpTest { 
         public  static Log logger = LogFactory.getLog(FtpTest. class); 

         private  static String userName;          //FTP 登录用户名 
         private  static String password;          //FTP 登录密码 
         private  static String ip;                      //FTP 服务器地址IP地址 
         private  static  int port;                         //FTP 端口 
         private  static Properties property =  null;     //属性集 
         private  static String configFile =  "E:\\test\\comftp\\ftpconfig.properties";     //配置文件的路径名 
         private  static FTPClient ftpClient =  null//FTP 客户端代理 
         //时间格式化 
         private  static SimpleDateFormat dateFormat =  new SimpleDateFormat( "yyyy-MM-dd hh:mm"); 
         //FTP状态码 
         public  static  int i = 1; 

         public  static  void main(String[] args) { 
                connectServer(); 
                setFileType(FTP.BINARY_FILE_TYPE); // 设置传输二进制文件 
                uploadManyFile( new File( "C:\\ooo\\upx"),  new File( "C:\\ooo\\upx"),  "/admin/ttt"); 
                closeConnect(); // 关闭连接 
        } 

         /** 
         * 上传单个文件,并重命名 
         * 
         * @param localFile--本地文件路径 
         * @param distFolder--新的文件名,可以命名为空"" 
         * @return true 上传成功,false 上传失败 
         */
 
         public  static  boolean uploadFile(File localFile,  final File localRootFile,  final String distFolder) { 
                System.out.println( "                    -------------------------"); 
                 boolean flag =  true
                 try { 
                        connectServer(); 
                        ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
                        ftpClient.enterLocalPassiveMode(); 
                        ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 
                        InputStream input =  new FileInputStream(localFile); 
//                        if (input == null) { 
//                                System.out.println("本地文件"+localFile.getPath()+"不存在!"); 
//                        } 
//                        if (newFileName.trim().equals("")) { 
//                                newFileName = localFile.getName(); 
//                        } 

                        String furi1 = localFile.getParentFile().getAbsoluteFile().toURI().toString(); 
                        String furi2 = localRootFile.getParentFile().getAbsoluteFile().toURI().toString(); 

                        String objFolder = distFolder + File.separator + furi1.substring(furi2.length()); 

                        ftpClient.changeWorkingDirectory( "/"); 
                        ftpClient.makeDirectory(objFolder); 
                        System.out.println( "a>>>>>>> : " + distFolder + File.separator + localFile.getParent()); 
                        System.out.println( "x>>>>>>> : " + objFolder); 
                        ftpClient.changeWorkingDirectory(objFolder); 

                        System.out.println( "b>>>>>>> : " + localFile.getPath() +  " " + ftpClient.printWorkingDirectory()); 
                        flag = ftpClient.storeFile(localFile.getName(), input); 
                         if (flag) { 
                                System.out.println( "上传文件成功!"); 
                        }  else { 
                                System.out.println( "上传文件失败!"); 
                        } 
                        input.close(); 
                }  catch (IOException e) { 
                        e.printStackTrace(); 
                        logger.debug( "本地文件上传失败!", e); 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
                 return flag; 
        } 

         /** 
         * 上传多个文件 
         * 
         * @param localFile--本地文件夹路径 
         * @return true 上传成功,false 上传失败 
         */
 
         public  static String uploadManyFile(String localFile) { 
                 boolean flag =  true
                StringBuffer strBuf =  new StringBuffer(); 
                 try { 
                        connectServer(); 
                        File file =  new File(localFile);         // 在此目录中找文件 
                        File fileList[] = file.listFiles(); 
                         for (File f : fileList) { 
                                 if (f.isDirectory()) {             // 文件夹中还有文件夹 
                                        uploadManyFile(f.getAbsolutePath()); 
                                }  else { 
                                } 
                                 if (!flag) { 
                                        strBuf.append(f.getName() +  "\r\n"); 
                                } 
                        } 
                        System.out.println(strBuf.toString()); 
                }  catch (NullPointerException e) { 
                        e.printStackTrace(); 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                        logger.debug( "本地文件上传失败!", e); 
                } 
                 return strBuf.toString(); 
        } 

         /** 
         * 上传多个文件 
         * 
         * @param localFile,--本地文件夹路径 
         * @param distFolder--目标路径 
         * @return true 上传成功,false 上传失败 
         */
 
         public  static String uploadManyFile(File localFile,  final File localRootFile,  final String distFolder) { 
                System.out.println( "-------------------------"); 
                 boolean flag =  true
                StringBuffer strBuf =  new StringBuffer(); 
                 int n = 0; 
                 try { 
                        connectServer(); 
                        ftpClient.makeDirectory(distFolder + File.separator + localFile.getParent()); 
                        File fileList[] = localFile.listFiles(); 
                         for (File upfile : fileList) { 
                                 if (upfile.isDirectory()) { // 文件夹中还有文件夹 
                                        uploadManyFile(upfile, localRootFile, distFolder); 
                                }  else { 
                                        flag = uploadFile(upfile, localRootFile, distFolder); 
                                } 
                                 if (!flag) { 
                                        strBuf.append(upfile.getName() +  "\r\n"); 
                                } 
                        } 
                        System.out.println(strBuf.toString()); 
                }  catch (NullPointerException e) { 
                        e.printStackTrace(); 
                        logger.debug( "本地文件上传失败!找不到上传文件!", e); 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                        logger.debug( "本地文件上传失败!", e); 
                } 
                 return strBuf.toString(); 
        } 

         /** 
         * 下载文件 
         * 
         * @param remoteFileName             --服务器上的文件名 
         * @param localFileName--本地文件名 
         * @return true 下载成功,false 下载失败 
         */
 
         public  static  boolean loadFile(String remoteFileName, String localFileName) { 
                 boolean flag =  true
                connectServer(); 
                 // 下载文件 
                BufferedOutputStream buffOut =  null
                 try { 
                        buffOut =  new BufferedOutputStream( new FileOutputStream(localFileName)); 
                        flag = ftpClient.retrieveFile(remoteFileName, buffOut); 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                        logger.debug( "本地文件下载失败!", e); 
                }  finally { 
                         try { 
                                 if (buffOut !=  null
                                        buffOut.close(); 
                        }  catch (Exception e) { 
                                e.printStackTrace(); 
                        } 
                } 
                 return flag; 
        } 

         /** 
         * 删除一个文件 
         */
 
         public  static  boolean deleteFile(String filename) { 
                 boolean flag =  true
                 try { 
                        connectServer(); 
                        flag = ftpClient.deleteFile(filename); 
                         if (flag) { 
                                System.out.println( "删除文件成功!"); 
                        }  else { 
                                System.out.println( "删除文件失败!"); 
                        } 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
                 return flag; 
        } 

         /** 
         * 删除目录 
         */
 
         public  static  void deleteDirectory(String pathname) { 
                 try { 
                        connectServer(); 
                        File file =  new File(pathname); 
                         if (file.isDirectory()) { 
                                File file2[] = file.listFiles(); 
                        }  else { 
                                deleteFile(pathname); 
                        } 
                        ftpClient.removeDirectory(pathname); 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
        } 

         /** 
         * 删除空目录 
         */
 
         public  static  void deleteEmptyDirectory(String pathname) { 
                 try { 
                        connectServer(); 
                        ftpClient.removeDirectory(pathname); 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
        } 

         /** 
         * 列出服务器上文件和目录 
         * 
         * @param regStr --匹配的正则表达式 
         */
 
         public  static  void listRemoteFiles(String regStr) { 
                connectServer(); 
                 try { 
                        String files[] = ftpClient.listNames(regStr); 
                         if (files ==  null || files.length == 0) 
                                System.out.println( "没有任何文件!"); 
                         else { 
                                 for ( int i = 0; i < files.length; i++) { 
                                        System.out.println(files[i]); 
                                } 
                        } 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
        } 

         /** 
         * 列出Ftp服务器上的所有文件和目录 
         */
 
         public  static  void listRemoteAllFiles() { 
                connectServer(); 
                 try { 
                        String[] names = ftpClient.listNames(); 
                         for ( int i = 0; i < names.length; i++) { 
                                System.out.println(names[i]); 
                        } 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
        } 

         /** 
         * 关闭连接 
         */
 
         public  static  void closeConnect() { 
                 try { 
                         if (ftpClient !=  null) { 
                                ftpClient.logout(); 
                                ftpClient.disconnect(); 
                        } 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
        } 

         /** 
         * 设置配置文件 
         * 
         * @param configFile 
         */
 
         public  static  void setConfigFile(String configFile) { 
                FtpTest.configFile = configFile; 
        } 

         /** 
         * 设置传输文件的类型[文本文件或者二进制文件] 
         * 
         * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE 
         * 
         */
 
         public  static  void setFileType( int fileType) { 
                 try { 
                        connectServer(); 
                        ftpClient.setFileType(fileType); 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
        } 

         /** 
         * 扩展使用 
         * 
         * @return ftpClient 
         */
 
         protected  static FTPClient getFtpClient() { 
                connectServer(); 
                 return ftpClient; 
        } 

         /** 
         * 设置参数 
         * 
         * @param configFile --参数的配置文件 
         */
 
         private  static  void setArg(String configFile) { 
                property =  new Properties(); 
                BufferedInputStream inBuff =  null
                 try { 
                        File file =  new File(configFile); 
                        inBuff =  new BufferedInputStream( new FileInputStream(file)); 
                        property.load(inBuff); 
                        userName = property.getProperty( "username"); 
                        password = property.getProperty( "password"); 
                        ip = property.getProperty( "ip"); 
                        port = Integer.parseInt(property.getProperty( "port")); 
                }  catch (FileNotFoundException e1) { 
                        System.out.println( "配置文件 " + configFile +  " 不存在!"); 
                }  catch (IOException e) { 
                        System.out.println( "配置文件 " + configFile +  " 无法读取!"); 
                } 
        } 

         /** 
         * 连接到服务器 
         * 
         * @return true 连接服务器成功,false 连接服务器失败 
         */
 
         public  static  boolean connectServer() { 
                 boolean flag =  true
                 if (ftpClient ==  null) { 
                         int reply; 
                         try { 
                                setArg(configFile); 
                                ftpClient =  new FTPClient(); 
                                ftpClient.setControlEncoding( "GBK"); 
                                ftpClient.setDefaultPort(port); 
                                ftpClient.configure(getFtpConfig()); 
                                ftpClient.connect(ip); 
                                ftpClient.login(userName, password); 
                                ftpClient.setDefaultPort(port); 
                                 //System.out.print(ftpClient.getReplyString()); 
                                reply = ftpClient.getReplyCode(); 
                                ftpClient.setDataTimeout(120000); 

                                 if (!FTPReply.isPositiveCompletion(reply)) { 
                                        ftpClient.disconnect(); 
                                        System.err.println( "FTP server refused connection."); 
                                         // logger.debug("FTP 服务拒绝连接!"); 
                                        flag =  false
                                } 
//                                System.out.println(i); 
                                i++; 
                        }  catch (SocketException e) { 
                                flag =  false
                                e.printStackTrace(); 
                                System.err.println( "登录ftp服务器 " + ip +  " 失败,连接超时!"); 
                        }  catch (IOException e) { 
                                flag =  false
                                e.printStackTrace(); 
                                System.err.println( "登录ftp服务器 " + ip +  " 失败,FTP服务器无法打开!"); 
                        } 
                } 
                 return flag; 
        } 

         /** 
         * 进入到服务器的某个目录下 
         * 
         * @param directory 
         */
 
         public  static  void changeWorkingDirectory(String directory) { 
                 try { 
                        connectServer(); 
                        ftpClient.changeWorkingDirectory(directory); 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
        } 

         /** 
         * 返回到上一层目录 
         */
 
         public  static  void changeToParentDirectory() { 
                 try { 
                        connectServer(); 
                        ftpClient.changeToParentDirectory(); 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
        } 

         /** 
         * 重命名文件 
         * 
         * @param oldFileName --原文件名 
         * @param newFileName --新文件名 
         */
 
         public  static  void renameFile(String oldFileName, String newFileName) { 
                 try { 
                        connectServer(); 
                        ftpClient.rename(oldFileName, newFileName); 
                }  catch (IOException ioe) { 
                        ioe.printStackTrace(); 
                } 
        } 

         /** 
         * 设置FTP客服端的配置--一般可以不设置 
         * 
         * @return ftpConfig 
         */
 
         private  static FTPClientConfig getFtpConfig() { 
                FTPClientConfig ftpConfig =  new FTPClientConfig(FTPClientConfig.SYST_UNIX); 
                ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); 
                 return ftpConfig; 
        } 

         /** 
         * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码 
         * 
         * @param obj 
         * @return "" 
         */
 
         private  static String iso8859togbk(Object obj) { 
                 try { 
                         if (obj ==  null
                                 return ""; 
                         else 
                                 return  new String(obj.toString().getBytes( "iso-8859-1"),  "GBK"); 
                }  catch (Exception e) { 
                         return ""; 
                } 
        } 

         /** 
         * 在服务器上创建一个文件夹 
         * 
         * @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... 
         */
 
         public  static  boolean makeDirectory(String dir) { 
                connectServer(); 
                 boolean flag =  true
                 try { 
                         // System.out.println("dir=======" dir); 
                        flag = ftpClient.makeDirectory(dir); 
                         if (flag) { 
                                System.out.println( "make Directory " + dir +  " succeed"); 

                        }  else { 

                                System.out.println( "make Directory " + dir +  false"); 
                        } 
                }  catch (Exception e) { 
                        e.printStackTrace(); 
                } 
                 return flag; 
        } 

}
 
运行结果表名,上传文件夹成功!
下载文件夹还没有实现。
 
另外,我将我用的新开发包也放出来,参看 [url]http://www.enterprisedt.com/[/url]
 


本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/100386,如需转载请自行联系原作者
相关文章
|
6月前
|
运维 Linux Apache
Linux Apache服务详解——Apache虚拟目录与禁止显示目录列表实战
Linux Apache服务详解——Apache虚拟目录与禁止显示目录列表实战
93 2
|
6月前
|
中间件 Go 开发者
Go net http包
Go net http包
60 0
|
14天前
|
开发框架 .NET 测试技术
了解 .NET 9 中的新 Microsoft.AspNetCore.OpenApi 包,并将其与 NSwag 和 Swashbuckle.AspNetCore 进行比较。
本文介绍了 `.NET 9` 中新推出的 `Microsoft.AspNetCore.OpenApi` 包,该包旨在为 `ASP.NET Core` 应用程序生成 `OpenAPI` 文档。文章对比了 `NSwag` 和 `Swashbuckle.AspNetCore` 两大现有库,探讨了新包的优势和不足,特别是在性能和功能方面。尽管新包在某些方面尚不及成熟库完善,但其对原生 `AoT` 编译的支持和未来的扩展潜力使其成为一个值得考虑的选择。文章还提供了详细的性能测试数据和优化建议,适合对 `OpenAPI` 文档生成感兴趣的开发者阅读。
34 3
了解 .NET 9 中的新 Microsoft.AspNetCore.OpenApi 包,并将其与 NSwag 和 Swashbuckle.AspNetCore 进行比较。
|
16天前
|
分布式计算 大数据 Apache
利用.NET进行大数据处理:Apache Spark与.NET for Apache Spark
【10月更文挑战第15天】随着大数据成为企业决策和技术创新的关键驱动力,Apache Spark作为高效的大数据处理引擎,广受青睐。然而,.NET开发者面临使用Spark的门槛。本文介绍.NET for Apache Spark,展示如何通过C#和F#等.NET语言,结合Spark的强大功能进行大数据处理,简化开发流程并提升效率。示例代码演示了读取CSV文件及统计分析的基本操作,突显了.NET for Apache Spark的易用性和强大功能。
28 1
|
3月前
|
分布式计算 大数据 Apache
跨越界限:当.NET遇上Apache Spark,大数据世界的新篇章如何谱写?
【8月更文挑战第28天】随着信息时代的发展,大数据已成为推动企业决策、科研与技术创新的关键力量。Apache Spark凭借其卓越的分布式计算能力和多功能数据处理特性,在大数据领域占据重要地位。然而,对于.NET开发者而言,如何在Spark生态中发挥自身优势成为一个新课题。为此,微软与Apache Spark社区共同推出了.NET for Apache Spark,使开发者能用C#、F#等语言编写Spark应用,不仅保留了Spark的强大功能,还融合了.NET的强类型系统、丰富库支持及良好跨平台能力,极大地降低了学习门槛并拓展了.NET的应用范围。
68 3
|
3月前
|
Ubuntu Linux 测试技术
在Linux中,已知 apache 服务的访问日志按天记录在服务器本地目录/app/logs 下,由于磁盘空间紧张现在要求只能保留最近7天的访问日志,请问如何解决?
在Linux中,已知 apache 服务的访问日志按天记录在服务器本地目录/app/logs 下,由于磁盘空间紧张现在要求只能保留最近7天的访问日志,请问如何解决?
|
3月前
|
Java Spring API
Spring框架与GraphQL的史诗级碰撞:颠覆传统,重塑API开发的未来传奇!
【8月更文挑战第31天】《Spring框架与GraphQL:构建现代API》介绍了如何结合Spring框架与GraphQL构建高效、灵活的API。首先通过引入`spring-boot-starter-data-graphql`等依赖支持GraphQL,然后定义查询和类型,利用`@GraphQLQuery`等注解实现具体功能。Spring的依赖注入和事务管理进一步增强了GraphQL服务的能力。示例展示了从查询到突变的具体实现,证明了Spring与GraphQL结合的强大潜力,适合现代API设计与开发。
118 0
|
5月前
|
Java 数据库连接 Apache
深入理解Apache Commons Pool2池化技术
深入理解Apache Commons Pool2池化技术
|
5月前
|
网络协议 Java 程序员
TCP/IP协议栈是网络通信基础,Java的`java.net`包提供工具,使开发者能利用TCP/IP创建网络应用
【6月更文挑战第23天】 **TCP/IP协议栈是网络通信基础,它包含应用层(HTTP, FTP等)、传输层(TCP, UDP)、网络层(IP)、数据链路层(帧, MAC地址)和物理层(硬件信号)。Java的`java.net`包提供工具,使开发者能利用TCP/IP创建网络应用,如Socket和ServerSocket用于客户端和服务器通信。**
53 3
|
5月前
|
存储 安全 Unix
【.Net Core】深入理解IO之文件和目录
【.Net Core】深入理解IO之文件和目录
53 4

热门文章

最新文章

推荐镜像

更多