高效编程之IDE的设置

来源:互联网 发布:java web后台开发 编辑:程序博客网 时间:2024/05/20 14:27

目录(?)[+]

  1. 一IDE配置篇
    1. 1代码自动提示
    2. 2XML自动提示
    3. 3注释自动生成
    4. 4 皮肤选择
    5. 4快捷操作键使用
  2. 二规范工程篇
    1. 1代码注释风格
    2. 2代码命名
    3. 3数据库规范
    4. 4性能规范
      1. 41 日志处理
      2. 43 对象创建销毁处理
      3. 44 数组集合处理
      4. 45 IO处理
      5. 46 其他规则
  3. 三常用代码篇
    1. 1日期处理类
    2. 2字符串处理类
    3. 3文件处理类
    4. 4DAO基类
    5. 6 JSON处理类
  4. 四常用框架
    1. 1日志打印-快速定位错
    2. 2Maven-jar的自动管理
    3. 3MyBatis自动代码生成
    4. 4SVN使用
  5. 五其它辅助工具

       林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

       摘要:在程序开发过程中,一些IDE的配置、常用代类的积累以及常用框架的使用。能帮助我们迅速写好代码,快速定位错误。同时,又有利于我们快速构造和部署,以及进行后续的迭代开发。

目录:

一、IDE配置篇

二、规范工程篇

三、常用代码篇

四、常用框架篇

五、其它工具

一、IDE配置篇

       平时开发因为是选用Eclipse,所以在配置上如果一开始就配置好的话,开发的过程中就可以省去很多步骤。首先是IDE的选择,这里因为平时用得最多的是Eclipse,所以主要还是针对它来说。到官网上去下载IDE,如果不做JAVA EE开发,建议选择第二个,当然。如果做安卓开发,也可以直接去下一直带有安卓SDK的Eclipse.


1.1、代码自动提示

        Eclipse代码里面的代码提示功能默认是关闭的,只有输入“.”的时候才会提示功能,下面说一下如何修改eclipse配置,开启代码自动提示功能  Eclipse  -> Window -> Perferences->Java -> Editor -> Content Assist 下面有三个选项,找到第二个“Auto activation triggers for Java:”选项  在其后的文本框中会看到一个“.”存在。这表示:只有输入“.”之后才会有代码提示和自动补全,我们要修改的地方就是这里。把该文本框中的“.”换掉,换成“abcdefghijklmnopqrstuvwxyz.”,这样,你在Eclipse里面写Java代码就可以做到按“abcdefghijklmnopqrstuvwxyz.”中的任意一个字符都会有代码提示。

这是下个自动提示的例子


1.2、XML自动提示

          在ssh或ssm框架中,都要写很多的XML配置代码。如果能在写的时候,自动显示一些提示代码,那就可以很快速的把代码写出来。

DTD 类型约束文件
         1. Window->Preferences->XML->XML Catalog->User Specified Entries窗口中,选择Add 按纽
         2.在Add XML Catalog Entry 对话框中选择或输入以下内容:
         Location: F:/soft/programmingSoft/Framework/Ibatis/sql-map-config-2.dtd
         Key Type: URI
        KEY: http://ibatis.apache.org/dtd/sql-map-config-2.dtd

XSD 类型约束文件

       1. Window->Preferences->XML->XML Catalog->User Specified Entries窗口中,选择Add 按纽
       2.在Add XML Catalog Entry 对话框中选择或输入以下内容:
       Location: F:/soft/programmingSoft/Framework/Spring/spring-framework-2.5.6.SEC01-with-dependencies/spring-framework-2.5.6.SEC01/dist/resources/spring-beans-2.5.xsd
       Key Type: Schema Location
       KEY: http://www.springframework.org/schema/beans/spring-beans-2.5.xsd



1.3、注释自动生成

      1、Java代码自动注释

      在使用Eclipse 编写Java代码时,自动生成的注释信息都是按照预先设置好的格式生成的。
      打开Windows->Preferences->Java->Code Style->Code Templates,点击右边窗口中的Comments,可以看到有很多选项,我们便可对此注释信息模板进行编辑。


如我们希望在一个Java文件的开头设置作者信息、日期信息。

为类和方法做注释标准

      

  

注:方法的注释自动生成方式为:输入/** 然后按下enter即可。


或者在你需要添加注释的地方点击Sources->Ganarate Element Comment,或者使用快捷键 Alt+Shift+J ,则 eclipse 自动在该类前面添加注释。
2、jsp 文件部分
       eclipse–>windows–>preferences–>Web–>JSP Files–>Editer–>Templates–>New JSP File–>单击[edit]按钮
在文件首行,添加如下内容:
Java代码
<%–
创建时间:date{time}
创 建 人:daniel
相关说明:
JDK1.6.0_21 tomcat6.0.29 servlet2.5
–%>
<%–
创建时间:date{time}
创 建 人:daniel
相关说明:
JDK1.6.0_21 tomcat6.0.29 servlet2.5
–%>
这样再创建 .java 或 .jsp 文件时,eclipse 就会为我们自动将注释写好。你还可以通过“导出”、“导入”功能,把自己的模板导出来,方便在其他机器上使用。

1.4 皮肤选择

     在开发过程中,是不是感到白色的一片看得很不舒服,特别是晚上的时候,屏幕太亮了,对眼晴实在不好。所幸Eclipse有这方面的皮肤库。在Eclipse lua中有自带的一个皮肤库Dark,选择方法

Window—>Preferences—>General—>Apperance选择主题为Dark,确认

结果如下



更多的皮肤模板请到这里来下吧!

eclipsecolorthemes.org


1.4、快捷操作键使用

快捷操作平时是我使用最多的,用键盘的速度肯定比用鼠标来得快,高手都是直接快捷键来定位各种问题。下面是一些我自己比较常用的快捷键,有兴趣的人也可以自己去百度下。

1、Ctrl+Shift+t:打开类型

如果你不是有意磨洋工,还是忘记通过源码树(source tree)打开的方式吧。用eclipse很容易打开接口的实现类

2、Alt+左右方向键:返回与前进

我们经常会遇到看代码时Ctrl+左键,层层跟踪,然后迷失在代码中的情况,这时只需要按“Alt+左方向键”就可以退回到上次阅读的位置,同理,按“Alt+右方向键”会前进到刚才退回的阅读位置,就像浏览器的前进和后退按钮一样。

 3、Ctrl+Shift+o:自动导入包

        4、Ctrl+Shift+r:打开资源
        这可能是所有快捷键组合中最省时间的了。这组快捷键可以让你打开你的工作区中任何一个文件,而你只需要按下文件名或mask名中的前几个字母,比如applic*.xml。美中不足的是这组快捷键并非在所有视图下都能用。

        5、Ctrl+Shift+s:自动添加方法

      可以添加一此set/get的方法,或toString等方法

       6、Ctrl+Shift+/添加注释,也可以用Ctrl+Shift+\取消注释

      7、Ctrl+o:快速outline

      如果想要查看当前类的方法或某个特定方法,但又不想把代码拉上拉下,也不想使用查找功能的话,就用ctrl+o吧。它可以列出当前类中的所有方法及属性,你只需输入你想要查询的方法名,点击enter就能够直接跳转至你想去的位置。

      8、ctrl+f:快速查找
      9. alt+shift+r:重命名(或者F2)

      重命名属性及方法在几年前还是个很麻烦的事,需要大量使用搜索及替换,以至于代码变得零零散散的。今天的Java IDE提供源码处理功能,Eclipse也是一样。现在,变量和方法的重命名变得十分简单,你会习惯于在每次出现更好替代名称的时候都做一次重命名。要使 用这个功能,将鼠标移动至属性名或方法名上,按下alt+shift+r,输入新名称并点击回车。就此完成。如果你重命名的是类中的一个属性,你可以点击alt+shift+r两次,这会呼叫出源码处理对话框,可以实现get及set方法的自动重命名。
    10.、ctrl+.及ctrl+1:下一个错误及快速修改
ctrl+.将光标移动至当前文件中的下一个报错处或警告处。这组快捷键我一般与ctrl+1一并使用,即修改建议的快捷键。新版Eclipse的修改建 议做的很不错,可以帮你解决很多问题,如方法中的缺失参数,throw/catch exception,未执行的方法等等

     11、快速复制一行

将光标放到某一行,按住Ctrl+Alt+Down,即可以在下面快速复制一行,按住Ctrl+Alt+Up,即可以在上面快速复制一行。

5、代码质量工具

二、规范工程篇

        软件开发是一个集体协作的过程,程序员之间的代码经常进行交换阅读,因此,Java源程序有一些约定俗成的命名规定,主要目的是为了提高Java程序的可读性以及管理上的方便性。好的程序代码应首先易于阅读,其次才是效率高低的问题。

2.1、代码注释风格

代码注释原则
       1. 注释应该简单清晰,避免使用装饰性内容,也就是说,不要使用象广告横幅那样的注释语句。
       2. 代码注释的目的是要使代码更易于被同时参与程序设计的开发人员以及其他后继开发人员理解。
       3. 先写注释,后写代码。
       写代码注释的最好方法是在写代码之前就写注释。这使你在写代码之前可以想想代码的功能和运行。而且这样确保不会遗漏注释。(如果程序的逻辑稍微复杂点的话,这样做非常有效)
       4. 注释信息不仅要包括代码的功能,还应给出原因。
例如,下面例 1 中的代码显示金额在 1,0001,000)的定单可给予 5% 的折扣。为什么要这样做呢?难道有一个商业法则规定大额定单可以得到折扣吗?这种给大额定单的特殊是有时限的呢,还是一直都这样?最初的程序设计者是否只是由于慷慨大度才这样做呢?除非它们在某个地方(或者是在源代码本身,或者是在一个外部文档里)被注释出来,否则你不可能知道这些。
if (grandTotal >= 1000.00)
{
grandTotal = grandTotal * 0.95;
}

更加详细的内容请看我的另一个博文这里:http://blog.csdn.net/evankaka/article/details/46538109

2.2、代码命名

命名总体原则
       1. 名字含义要明确,做到见名知义,如: User,Role, UserManager
       2. 尽量使用英文名字作为变量名,如果要使用中文,请写上备注.
       如:var hbType = null;// hb是中文“货币”的首字母缩写.
       3. 采用大小写混合形式命名,提高名字的可读性
       正确:UserManager
       错误: usermanager
       4. 尽量少用缩写,但如果一定要使用,就要谨慎地使用。
       应该保留一个标准缩写的列表,并且在使用时保持一致。例如,想对单词“number”采用缩写,使用 num 这种格式,并且只使用这一种形式.注意:要维护缩写词汇列表.
       5. 所有文件的名称都是大写字母开头,大小写混合, 如UserList.jsp
       6. 所有目录的名称都是小写字母开头,大小写混合, 如userType
       7. 变量名不能以下划线开头,如“_account”,”_userName”是不允许的,因为下划线开头的变量可能被OWK平台做为保留字占用.
       8. 避免使用相似或者仅在大小写上有区别的名字
       例如,不应同时使用变量名 persistentObject 和 persistentObjects,以及 anSqlDatabase 和 anSQLDatabase。

命名

包结构定义=[.{包单元}]*
说明:
       1:一个包是由一个或多个构造单元组成,各构造单元之间以点号”.”隔开
       2:一个包单元由一个或多个词组成
       3:包单元应该是名词
       • 业务系统的包结构是com.cmb.zct..{模块名}
       • 包名全部小写,如:com.cmb.zct.tx.OA.common是不允许的.但有种情况下允许出现大写字母,就是当包单元是由多个词组成时.如: com.cmb.zct.tx.oa.userType.

       • 使用完全的英文描述符,所有单词的第一个字母要大写,并且单词中大小写混合。
       • 类名是名词或名词词组.如 LogManager
       • 工具类以Util结尾 . 如FileUtil,StrUtil
       • 异常类以Exception结尾.如RootDirNotExistsException
       • 抽象类名以Abstract开头 AbstractGenerator
       • 工厂类以Factory结尾,如 ConnFactory
       • 接口同类名,大小写混合..

方法
       • 成员函数的命名应采用完整的英文描述符,大小写混合使用:所有中间单词的第一个字母大写。成员函数名称的第一个单词常常采用一个有强烈动作色彩的动词。首个单词小写。如:getUserInfo, removeEquipment
参数变量
       以 小写p开头
       如
       public void sendMessage(String pMessage){
       ……………
       }
注意:javabean 的参数变量不带p。
常量名
       采用完整的英文大写单词,在词与词之间用下划线连接。MAX_VALUE,DEFAULT_START_DATE
目录名
       同包名,小写字母开头,如果有多个单词构成,则第2个以后的单词以大写字母开头。如user, userType目录
文件名
       同类名命名规则,大写字母开头,大小写混合。如:EquipmentList.jsp
       模块相关文件命名约束,为了方便说明,{MODEL_NAME}代表实际模块的名称,那各文件的名字必须满足下表格式要求.<br><strong>文件                                   格式                                     举例</strong><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业务组件接口    I{MODEL_NAME}Facade.java IUserFacade.java
       服务组件接口 I{MODEL_NAME}Service.java    IUserService.java<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业务组件实现类{MODEL_NAME}FacadeImpl.java UserFacadeImpl.java
       服务组件实现类 {MODEL_NAME}ServiceImpl.java    IUserServiceImpl.java<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;测试类{MODEL_NAME}ServiceTest.java UserServiceTest.java
       更加详细的内容请看我的另一个博文这里:http://blog.csdn.net/evankaka/article/details/46538109

2.3、数据库规范

 命名规范
1、 库表名、字段名尽量不用缩写(英文单词太长可适当缩写,但要能让人看明白含义,同一英语单词的缩写需保持一致)
2、 表名、字段名的各单词间必须用下划线分隔开
如 表名:USER_INFO 字段名:USER_CODE, USER_NAME
3、 必须为每个子系统定义独立的schema
代码编写规范
1、 对数据库表、存储过程的访问必须显示加上schema名称(mysql也叫database);
2、 不允许使用select * from 编写查询语句,必须显示写查询字段列表;
3、 不允许跨子系统直接访问库表,跨子系统必须通过服务接口进行调用;
4、 批量操作必须采用jdbc的batch方式提交;
5、 尽量使用JDK自带的API函数,不要自己写类似功能的函数;
6、 Public方法中,对外部传入的不可信任的参数,需要进行有效性校验;

2.4、性能规范

2.4.1 日志处理

1. 避免显式调用对象的toString方法

[java] view plain copy
print?
  1. Object param1 = “param1”;  
  2. // 显式调用toString  
  3. // 当当前日志级别为 info时,虽然没有打印到文件中,但是在方法调用参数传递时,已经做了一次toString的方法。  
  4. LOGGER.debug(”打印一个参数:{}.”, param1.toString());  
  5. // 正确的方式:  
  6. LOGGER.debug(”打印一个参数:{}.”, param1);  
Object param1 = "param1";// 显式调用toString// 当当前日志级别为 info时,虽然没有打印到文件中,但是在方法调用参数传递时,已经做了一次toString的方法。LOGGER.debug("打印一个参数:{}.", param1.toString());// 正确的方式:LOGGER.debug("打印一个参数:{}.", param1);
2. 对类中日志工具对象logger应声明为static。尽管一些logger对LogFactory工厂有一些优化,但是我们也必须防止代码没有必要的运行。
3. 避免在循环中打印大量的日志。
2.4.2 字符串处理
1. 对于常量字符串,不要通过new方式来创建;
2. 对于常量字符串之间的拼接,请使用“+”;对于字符串变量(不能在编译期间确定其具体值的字符串对象)之间的拼接,请使用StringBuilder/StringBuffer;
3. 在使用StringBuilder/StringBuffer进行字符串操作时,请尽量设定初始容量大小;也尽量避免通过String/CharSequence对象来构建StringBuffer对象(即:不要使用 new StringBuilder(String) 这个构造方法来创建StringBuilder对象);
4. 当查找字符串时,如果不需要支持正则表达式请使用indexOf(…)实现查找(特殊情况可以使用startsWith和endsWith);当需要支持正则表达式时,如果需要频繁的进行查找匹配,请直接使用正则表达式工具类实现查找;
5. 尽量避免使用String的split方法。
除非是必须的,否则应该避免使用split,split由于支持正则表达式,所以效率比较低,如果是频繁的几十,几百万的调用将会耗费大量资源,如果确实 需要频繁的调用split,可以考虑使用apache的StringUtils.split(string,char),频繁split的可以缓存结果。
6.

2.4.3 对象创建、销毁处理

1. 在循环外定义变量;
2. 对局部变量不需要显式设置为null;
3. 尽量避免非常大的内存分配。
从数据库中读取的记录放到集合中时,要注意控制集合元素个数。
4.

2.4.4 数组、集合处理

1. 数组的复制使用System.arraycopy(…)方法;
2. 对于数组、集合的拷贝、查找、排序等操作,如果是一般应用,可以优先采用java.util.Arrays和java.util.Collections 中提供的工具方法;但是对于热点代码,最好是参考java API中的方法实现,自己开发特定的排序等方法,以减少临时对象的创建;
3. 当需要在方法之间传递多个属性值时,从性能角度考虑,应优先采用结构体,而非ArrayList或Vector等集合类;
4. 在代码开发中,需要根据应用场景合理选择集合框架中的集合类,应用场景可按单线程和多线程来划分,也可按频繁插入、随机提取等具体操作场景来划分;
5. 定义集合对象时,请尽量设定初始容量大小;
6.

2.4.5 IO处理

1. 在IO操作中,必须定义finally代码段,并在该代码段中执行IO关闭操作;
2. 进行IO读写操作时,必须使用缓冲机制;
2.4.6 多线程处理
1. 避免太多的使用 synchronized 关键字。尽量减小Synchronized的范围。
2. 在线程池中运行的子线程,其run方法不可以往外抛出异常。

2.4.6 其他规则

1. 避免在循环中对变量进行重复计算
避免使用这类的语句:for(int i=0; i<list.size(); i++)
应该使用:int size=list.size(); for(int i=0; i<size; i++)
更加优化的是使用迭代的方式:for(Object o: list)

2. 异常只能用于错误处理,不应该用来控制代码流程
当创建一个异常时,需要收集一个栈跟踪(stack track),这个栈跟踪用于描述异常是在何处创建的。构建这些栈跟踪时需要为运行时栈做一份快照,正是这一部分开销很大。当需要创建一个 Exception时,JVM不得不说:先别动,我想就您现在的样子存一份快照,所以暂时停止入栈和出栈操作。栈跟踪不只包含运行时栈中的一两个元素,而是包含这个栈中的每一个元素。

三、常用代码篇

2.1、日期处理类

     日期处理主要完成了一些格式方面的转换

[java] view plain copy
print?
  1. import java.text.ParseException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.ArrayList;  
  4. import java.util.Calendar;  
  5. import java.util.Date;  
  6. import java.util.List;  
  7. import org.apache.commons.lang3.time.DateUtils;  
  8. import com.google.common.primitives.UnsignedBytes;  
  9. import com.lz.cts.common.errorcode.CtsErrorCode;  
  10. import com.lz.ctsframework.core.support.ServiceException;  
  11. /** 
  12.  *  
  13.  * <b>类说明:</b>日期工具类 
  14.  *  
  15.  * <p> 
  16.  * <b>详细描述:</b> 
  17.  *  
  18.  * @author ***** 
  19.  * @since ***** 
  20.  */  
  21. public class CtsDateUtil {  
  22.   
  23.     public final static String DATE_FROMAT = “yyyyMMdd”;  
  24.   
  25.     public final static String TIME_FORMAT = “HHmmss”;  
  26.   
  27.     /** 
  28.      * 两个日期是否在跨度之内 
  29.      *  
  30.      * @param startDate 
  31.      * @param endDate 
  32.      * @param gapType 
  33.      *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR 
  34.      * @param maxGap 
  35.      *            最大跨度值 
  36.      * @return 
  37.      */  
  38.     public static boolean isWithInDateGap(Date startDate, Date endDate,  
  39.             int gapType, int maxGap) {  
  40.         if (startDate == null) {  
  41.             throw new IllegalArgumentException(“The startDate must not be null”);  
  42.         }  
  43.         if (endDate == null) {  
  44.             throw new IllegalArgumentException(“The endDate must not be null”);  
  45.         }  
  46.         if (gapType != Calendar.YEAR && gapType != Calendar.MONTH  
  47.                 && gapType != Calendar.DAY_OF_YEAR) {  
  48.             throw new IllegalArgumentException(  
  49.                     ”The value of gapType is invalid”);  
  50.         }  
  51.   
  52.         Calendar start = Calendar.getInstance();  
  53.         start.setTime(startDate);  
  54.         start.add(gapType, maxGap);  
  55.         int compare = start.getTime().compareTo(endDate);  
  56.   
  57.         return compare >= 0;  
  58.     }  
  59.   
  60.     /** 
  61.      * 两个日期是否在跨度之内 
  62.      *  
  63.      * @param startDate 
  64.      * @param endDate 
  65.      * @param gapType 
  66.      *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR 
  67.      * @param maxGap 
  68.      *            最大跨度值 
  69.      * @return 
  70.      * @throws ParseException 
  71.      */  
  72.     public static boolean isWithInDateGap(String startDate, String endDate,  
  73.             int gapType, int maxGap){  
  74.         Date startDateTime = null;  
  75.         Date endDateTime = null;  
  76.         try{  
  77.             startDateTime = DateUtils.parseDate(startDate, DATE_FROMAT);  
  78.             endDateTime = DateUtils.parseDate(endDate, DATE_FROMAT);  
  79.         }catch(ParseException e){  
  80.             throw new ServiceException(*****,new String[]{“交易日期”}, “开始日期:” + startDate + “,结束日期:” + endDate);  
  81.         }  
  82.           
  83.         return isWithInDateGap(startDateTime,endDateTime, gapType, maxGap);  
  84.     }  
  85.   
  86.     /** 
  87.      * 两个日期是否在跨度之内 
  88.      *  
  89.      * @param startDate 
  90.      * @param endDate 
  91.      * @param gapType 
  92.      *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR 
  93.      * @param maxGap 
  94.      *            最大跨度值 
  95.      * @return 
  96.      * @throws ParseException 
  97.      */  
  98.     public static boolean isWithInDateGap(int startDate, int endDate,  
  99.             int gapType, int maxGap) throws ParseException {  
  100.         return isWithInDateGap(  
  101.                 DateUtils.parseDate(String.valueOf(startDate), DATE_FROMAT),  
  102.                 DateUtils.parseDate(String.valueOf(endDate), DATE_FROMAT),  
  103.                 gapType, maxGap);  
  104.     }  
  105.   
  106.     /** 
  107.      * <b>说明:</b> 获取系统当前日期 
  108.      *  
  109.      * @param 
  110.      * @return 
  111.      * @ 
  112.      * @author **** 
  113.      * @since 2014年5月22日 
  114.      */  
  115.     public static int getCurIntPcDate()  {  
  116.         return Integer.parseInt(getCurPcDate());  
  117.     }  
  118.   
  119.     /** 
  120.      * <b>说明:</b> 获取系统当前日期 
  121.      *  
  122.      * @param 
  123.      * @return 
  124.      * @ 
  125.      * @author **** 
  126.      * @since **** 
  127.      */  
  128.     public static String getCurPcDate() {  
  129.         java.util.Date currentDate = new java.util.Date();  
  130.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);  
  131.         return formatdate.format(currentDate);  
  132.     }  
  133.   
  134.     /*** 
  135.      * <b>说明:</b> 获取指定格式的系统当前日期 
  136.      * @param 
  137.      * @return  
  138.      * @ 
  139.      * @author **** 
  140.      * @since **** 
  141.      */  
  142.     public static String getCurPcDate(String strFormat)  
  143.     {  
  144.         java.util.Date currentDate = new java.util.Date();  
  145.         SimpleDateFormat formatdate = new SimpleDateFormat(strFormat);  
  146.         return formatdate.format(currentDate);  
  147.     }  
  148.   
  149.     /*** 
  150.      * <b>说明:</b>  获取当时系统日期时间【YYYYMMDDHHmmss】 
  151.      * @param 
  152.      * @return  
  153.      * @throws ServiceException 
  154.      * @author yanfy  
  155.      * @since 2014年6月5日 
  156.      */  
  157.     public static String getCurPcDateTime()  
  158.     {  
  159.         java.util.Date currentDate = new java.util.Date();  
  160.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT+TIME_FORMAT);  
  161.         return formatdate.format(currentDate);  
  162.     }  
  163.   
  164.     /** 
  165.      * <b>说明:</b> 获取当时系统日期时间【YYYYMMDDHHmmss】 
  166.      * @param 
  167.      * @return  
  168.      * @author **** 
  169.      * @since 2014年6月5日 
  170.      */  
  171.     public static Long getIntCurPcDateTime()  
  172.     {  
  173.         return Long.valueOf(getCurPcDateTime());  
  174.     }  
  175.   
  176.   
  177.     /** 
  178.      * <b>说明:</b> 获取系统当前时间 
  179.      *  
  180.      * @param 
  181.      * @return 当前时间并格式化成“HHmmss”,如“123124” 
  182.      * @ 
  183.      * @author **** 
  184.      * @since **** 
  185.      */  
  186.     public static String getCurPcTime()  {  
  187.         java.util.Date currentDate = new java.util.Date();  
  188.         SimpleDateFormat formatdate = new SimpleDateFormat(TIME_FORMAT);  
  189.         return formatdate.format(currentDate);  
  190.     }     
  191.   
  192.     /** 
  193.      * <b>说明: </b>验证传入数值型日期[YYYYMMDD]是否合法 
  194.      *  
  195.      * @param 
  196.      * @return 
  197.      * @ 
  198.      * @author **** 
  199.      * @return 
  200.      * @since ***** 
  201.      */  
  202.     public static boolean checkDateFormat(int intDate) {  
  203.         return checkDateFormat(String.valueOf(intDate));  
  204.     }  
  205.   
  206.     /** 
  207.      * <b>说明: </b>验证传入字符型日期[YYYYMMDD]是否合法 
  208.      *  
  209.      * @param 
  210.      * @return 
  211.      * @ 
  212.      * @author **** 
  213.      * @since **** 
  214.      */  
  215.     public static boolean checkDateFormat(String strDate) {  
  216.         return checkDateFormat(strDate, DATE_FROMAT);  
  217.     }  
  218.   
  219.     /** 
  220.      * <b>说明: </b>验证传入字符型日期是否合法 
  221.      *  
  222.      * @param 
  223.      * @return 
  224.      * @ 
  225.      * @author *** 
  226.      * @since **** 
  227.      */  
  228.     public static boolean checkDateFormat(int intDate, String strFormat) {  
  229.         return checkDateFormat(String.valueOf(intDate), DATE_FROMAT);  
  230.     }  
  231.   
  232.     /** 
  233.      * <b>说明: </b>验证传入字符型日期是否合法 
  234.      *  
  235.      * @param 
  236.      * @return 
  237.      * @ 
  238.      * @author **** 
  239.      * @since *** 
  240.      */  
  241.     public static boolean checkDateFormat(String strDate, String strFormat)  
  242.     {  
  243.         try {  
  244.             DateUtils.parseDateStrictly(strDate, strFormat);  
  245.             return true;  
  246.         } catch (ParseException e) {  
  247.             return false;  
  248.         }  
  249.     }  
  250.   
  251.     /** 
  252.      * <b>说明: </b>验证传入数值型时间[HH24MMSS]是否合法 
  253.      *  
  254.      * @param 
  255.      * @return 
  256.      * @ 
  257.      * @author **** 
  258.      * @return 
  259.      * @since **** 
  260.      */  
  261.     public static boolean checkTimeFormat(int intDate) {  
  262.         String strDate = String.valueOf(intDate);  
  263.         if(strDate.length() <6)  
  264.             strDate = CommUtil.LeftFill(strDate, ’0’6);  
  265.         System.out.println(”curTime:”+strDate);  
  266.         return checkTimeFormat(strDate);  
  267.     }  
  268.   
  269.     /** 
  270.      * <b>说明: </b>验证传入字符型时间[HH24MMSS]是否合法 
  271.      *  
  272.      * @param 
  273.      * @return 
  274.      * @ 
  275.      * @author **** 
  276.      * @since **** 
  277.      */  
  278.     public static boolean checkTimeFormat(String strDate) {  
  279.         return checkTimeFormat(strDate, TIME_FORMAT);  
  280.     }  
  281.   
  282.     /** 
  283.      * <b>说明: </b>验证传入字符型时间是否合法 
  284.      *  
  285.      * @param 
  286.      * @return 
  287.      * @ 
  288.      * @author **** 
  289.      * @since **** 
  290.      */  
  291.     public static boolean checkTimeFormat(int intDate, String strFormat) {  
  292.         return checkTimeFormat(String.valueOf(intDate), DATE_FROMAT);  
  293.     }  
  294.   
  295.     /** 
  296.      * <b>说明: </b>验证传入字符型时间是否合法 
  297.      *  
  298.      * @param 
  299.      * @return 
  300.      * @ 
  301.      * @author **** 
  302.      * @since *** 
  303.      */  
  304.     public static boolean checkTimeFormat(String strDate, String strFormat){  
  305.         try {  
  306.             DateUtils.parseDateStrictly(strDate, strFormat);  
  307.             return true;  
  308.         } catch (ParseException e) {  
  309.             return false;  
  310.         }  
  311.     }  
  312.   
  313.     /** 
  314.      * <b>说明: </b>日期转换 
  315.      * @param strDate 
  316.      * @return 
  317.      */  
  318.     public static Date parseDate(String strDate){  
  319.         return parseDate(strDate, DATE_FROMAT);  
  320.     }  
  321.     /** 
  322.      * <b>说明: </b>日期转换 
  323.      * @param strDate 
  324.      * @param strFormat 
  325.      * @return 
  326.      */  
  327.     public static Date parseDate(String strDate,String strFormat){  
  328.         try {  
  329.             return DateUtils.parseDateStrictly(strDate, strFormat);  
  330.         } catch (ParseException e) {  
  331.             throw new ServiceException(CtsErrorCode.ERROR_FORMAT,new String[]{“交易日期”}, “日期:” + strDate);  
  332.         }  
  333.     }  
  334.     /** 
  335.      * <b>说明: </b>日期转换 
  336.      * @param intDate 
  337.      * @param strFormat 
  338.      * @return 
  339.      */  
  340.     public static Date parseDate(int intDate,String strFormat){  
  341.         return parseDate(String.valueOf(intDate), strFormat);  
  342.     }  
  343.     /** 
  344.      * <b>说明: </b>日期转换 
  345.      * @param intDate 
  346.      * @return 
  347.      */  
  348.     public static Date parseDate(int intDate){  
  349.         return parseDate(String.valueOf(intDate));  
  350.     }  
  351.   
  352.     /** 
  353.      * 日期转换成字符串 
  354.      * @param date 
  355.      * @param dateFormat 
  356.      * @return 
  357.      */  
  358.     public static String date2String(Date date,String dateFormat) {  
  359.         SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);  
  360.         return formatdate.format(date);  
  361.     }  
  362.     /** 
  363.      * 日期转换成字符串 
  364.      * @param date 
  365.      * @param dateFormat 
  366.      * @return 格式为YYYYMMDD 
  367.      */  
  368.     public static String date2String(Date date) {  
  369.         return date2String(date,DATE_FROMAT);  
  370.     }  
  371.   
  372.     /** 
  373.      * 日期转换成整数 
  374.      * @param date 
  375.      * @param dateFormat 
  376.      * @return 格式为YYYYMMDD 
  377.      */  
  378.     public static int date2Int(Date date) {  
  379.         String str = date2String(date,DATE_FROMAT);  
  380.         return Integer.parseInt(str);  
  381.     }  
  382.   
  383.   
  384.     /*** 
  385.      * <b>说明:</b>  
  386.      * @param 
  387.      * @return  
  388.      * @throws ServiceException 
  389.      * @author **** 
  390.      * @since *** 
  391.      */  
  392.     public static String getCurrLastDay()  
  393.     {  
  394.         return getCurrAfterDay(1);  
  395.     }  
  396.     /*** 
  397.      * <b>说明:</b>  
  398.      * @param 
  399.      * @return  
  400.      * @throws ServiceException 
  401.      * @author **** 
  402.      * @since **** 
  403.      */  
  404.     public static String getCurrAfterDay(int days)  
  405.     {  
  406.         Calendar theCa = Calendar.getInstance();  
  407.         theCa.setTime(new Date());        
  408.         theCa.add(theCa.DATE, -1*days);  
  409.         Date date = theCa.getTime();  
  410.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);  
  411.         return formatdate.format(date);  
  412.     }  
  413.     /** 
  414.      * 获取交易日期之前的相隔天数的日期 
  415.      * @param transDate 交易日期 
  416.      * @param days 天数 
  417.      * @return 
  418.      * @author **** 
  419.      * @since *** 
  420.      */  
  421.     public static Integer getTransDateBeforeDay(Integer transDate,int days){  
  422.           
  423.         Calendar theCa = Calendar.getInstance();  
  424.         theCa.setTime(parseDate(transDate));          
  425.         theCa.add(Calendar.DATE, -1*days);  
  426.         Date date = theCa.getTime();  
  427.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);  
  428.         return Integer.valueOf(formatdate.format(date));  
  429.     }  
  430.       
  431.     /** 
  432.      * 获取指定日期之后的相隔n年的日期 
  433.      * @param transDate 
  434.      * @param years 
  435.      * @return 
  436.      * @return Integer 
  437.      */  
  438.     public static Integer getDateAfterYear(Integer transDate, int years) {  
  439.         Calendar theCa = Calendar.getInstance();  
  440.         theCa.setTime(parseDate(transDate));  
  441.         theCa.add(Calendar.YEAR, years);  
  442.         Date date = theCa.getTime();  
  443.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);  
  444.         return Integer.valueOf(formatdate.format(date));  
  445.     }  
  446.       
  447.     /** 
  448.      * 获取交易日期之后的相隔天数的日期 
  449.      * @param transDate 交易日期 
  450.      * @param days 天数 
  451.      * @return 
  452.      * @author **** 
  453.      * @since **** 
  454.      */  
  455.     public static Integer getTransDateAfterDay(Integer transDate,int days){  
  456.           
  457.         Calendar theCa = Calendar.getInstance();  
  458.         theCa.setTime(parseDate(transDate));          
  459.         theCa.add(Calendar.DATE, 1*days);  
  460.         Date date = theCa.getTime();  
  461.         SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);  
  462.         return Integer.valueOf(formatdate.format(date));  
  463.     }  
  464.           
  465.     /** 
  466.      * 计算两个日期相差的天数 
  467.      * @param beginDate 【YYYYMMDD】 
  468.      * @param endDate  【YYYYMMDD】 
  469.      * @return Integer  
  470.      * @author **** 
  471.      * @since **** 
  472.      */  
  473.     public static Integer diffDate(Integer beginDate,Integer endDate){                        
  474.             Calendar theCa1= Calendar.getInstance();    
  475.             Calendar theCa2= Calendar.getInstance();    
  476.             theCa1.setTime(parseDate(beginDate));    
  477.             theCa2.setTime(parseDate(endDate));        
  478.             long between_days=(theCa2.getTimeInMillis()-theCa1.getTimeInMillis())/(1000*3600*24);            
  479.             return Integer.parseInt(String.valueOf(between_days));    
  480.     }  
  481.       
  482.       
  483. }  
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.List;import org.apache.commons.lang3.time.DateUtils;import com.google.common.primitives.UnsignedBytes;import com.lz.cts.common.errorcode.CtsErrorCode;import com.lz.ctsframework.core.support.ServiceException;/** *  * <b>类说明:</b>日期工具类 *  * <p> * <b>详细描述:</b> *  * @author ***** * @since ***** */public class CtsDateUtil {    public final static String DATE_FROMAT = "yyyyMMdd";    public final static String TIME_FORMAT = "HHmmss";    /**     * 两个日期是否在跨度之内     *      * @param startDate     * @param endDate     * @param gapType     *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR     * @param maxGap     *            最大跨度值     * @return     */    public static boolean isWithInDateGap(Date startDate, Date endDate,            int gapType, int maxGap) {        if (startDate == null) {            throw new IllegalArgumentException("The startDate must not be null");        }        if (endDate == null) {            throw new IllegalArgumentException("The endDate must not be null");        }        if (gapType != Calendar.YEAR && gapType != Calendar.MONTH                && gapType != Calendar.DAY_OF_YEAR) {            throw new IllegalArgumentException(                    "The value of gapType is invalid");        }        Calendar start = Calendar.getInstance();        start.setTime(startDate);        start.add(gapType, maxGap);        int compare = start.getTime().compareTo(endDate);        return compare >= 0;    }    /**     * 两个日期是否在跨度之内     *      * @param startDate     * @param endDate     * @param gapType     *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR     * @param maxGap     *            最大跨度值     * @return     * @throws ParseException     */    public static boolean isWithInDateGap(String startDate, String endDate,            int gapType, int maxGap){        Date startDateTime = null;        Date endDateTime = null;        try{            startDateTime = DateUtils.parseDate(startDate, DATE_FROMAT);            endDateTime = DateUtils.parseDate(endDate, DATE_FROMAT);        }catch(ParseException e){            throw new ServiceException(*****,new String[]{"交易日期"}, "开始日期:" + startDate + ",结束日期:" + endDate);        }        return isWithInDateGap(startDateTime,endDateTime, gapType, maxGap);    }    /**     * 两个日期是否在跨度之内     *      * @param startDate     * @param endDate     * @param gapType     *            跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR     * @param maxGap     *            最大跨度值     * @return     * @throws ParseException     */    public static boolean isWithInDateGap(int startDate, int endDate,            int gapType, int maxGap) throws ParseException {        return isWithInDateGap(                DateUtils.parseDate(String.valueOf(startDate), DATE_FROMAT),                DateUtils.parseDate(String.valueOf(endDate), DATE_FROMAT),                gapType, maxGap);    }    /**     * <b>说明:</b> 获取系统当前日期     *      * @param     * @return     * @     * @author ****     * @since 2014年5月22日     */    public static int getCurIntPcDate()  {        return Integer.parseInt(getCurPcDate());    }    /**     * <b>说明:</b> 获取系统当前日期     *      * @param     * @return     * @     * @author ****     * @since ****     */    public static String getCurPcDate() {        java.util.Date currentDate = new java.util.Date();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);        return formatdate.format(currentDate);    }    /***     * <b>说明:</b> 获取指定格式的系统当前日期     * @param     * @return      * @     * @author ****     * @since ****     */    public static String getCurPcDate(String strFormat)    {        java.util.Date currentDate = new java.util.Date();        SimpleDateFormat formatdate = new SimpleDateFormat(strFormat);        return formatdate.format(currentDate);    }    /***     * <b>说明:</b>  获取当时系统日期时间【YYYYMMDDHHmmss】     * @param     * @return      * @throws ServiceException     * @author yanfy      * @since 2014年6月5日     */    public static String getCurPcDateTime()    {        java.util.Date currentDate = new java.util.Date();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT+TIME_FORMAT);        return formatdate.format(currentDate);    }    /**     * <b>说明:</b> 获取当时系统日期时间【YYYYMMDDHHmmss】     * @param     * @return      * @author ****     * @since 2014年6月5日     */    public static Long getIntCurPcDateTime()    {        return Long.valueOf(getCurPcDateTime());    }    /**     * <b>说明:</b> 获取系统当前时间     *      * @param     * @return 当前时间并格式化成“HHmmss”,如“123124”     * @     * @author ****     * @since ****     */    public static String getCurPcTime()  {        java.util.Date currentDate = new java.util.Date();        SimpleDateFormat formatdate = new SimpleDateFormat(TIME_FORMAT);        return formatdate.format(currentDate);    }       /**     * <b>说明: </b>验证传入数值型日期[YYYYMMDD]是否合法     *      * @param     * @return     * @     * @author ****     * @return     * @since *****     */    public static boolean checkDateFormat(int intDate) {        return checkDateFormat(String.valueOf(intDate));    }    /**     * <b>说明: </b>验证传入字符型日期[YYYYMMDD]是否合法     *      * @param     * @return     * @     * @author ****     * @since ****     */    public static boolean checkDateFormat(String strDate) {        return checkDateFormat(strDate, DATE_FROMAT);    }    /**     * <b>说明: </b>验证传入字符型日期是否合法     *      * @param     * @return     * @     * @author ***     * @since ****     */    public static boolean checkDateFormat(int intDate, String strFormat) {        return checkDateFormat(String.valueOf(intDate), DATE_FROMAT);    }    /**     * <b>说明: </b>验证传入字符型日期是否合法     *      * @param     * @return     * @     * @author ****     * @since ***     */    public static boolean checkDateFormat(String strDate, String strFormat)    {        try {            DateUtils.parseDateStrictly(strDate, strFormat);            return true;        } catch (ParseException e) {            return false;        }    }    /**     * <b>说明: </b>验证传入数值型时间[HH24MMSS]是否合法     *      * @param     * @return     * @     * @author ****     * @return     * @since ****     */    public static boolean checkTimeFormat(int intDate) {        String strDate = String.valueOf(intDate);        if(strDate.length() <6)            strDate = CommUtil.LeftFill(strDate, '0', 6);        System.out.println("curTime:"+strDate);        return checkTimeFormat(strDate);    }    /**     * <b>说明: </b>验证传入字符型时间[HH24MMSS]是否合法     *      * @param     * @return     * @     * @author ****     * @since ****     */    public static boolean checkTimeFormat(String strDate) {        return checkTimeFormat(strDate, TIME_FORMAT);    }    /**     * <b>说明: </b>验证传入字符型时间是否合法     *      * @param     * @return     * @     * @author ****     * @since ****     */    public static boolean checkTimeFormat(int intDate, String strFormat) {        return checkTimeFormat(String.valueOf(intDate), DATE_FROMAT);    }    /**     * <b>说明: </b>验证传入字符型时间是否合法     *      * @param     * @return     * @     * @author ****     * @since ***     */    public static boolean checkTimeFormat(String strDate, String strFormat){        try {            DateUtils.parseDateStrictly(strDate, strFormat);            return true;        } catch (ParseException e) {            return false;        }    }    /**     * <b>说明: </b>日期转换     * @param strDate     * @return     */    public static Date parseDate(String strDate){        return parseDate(strDate, DATE_FROMAT);    }    /**     * <b>说明: </b>日期转换     * @param strDate     * @param strFormat     * @return     */    public static Date parseDate(String strDate,String strFormat){        try {            return DateUtils.parseDateStrictly(strDate, strFormat);        } catch (ParseException e) {            throw new ServiceException(CtsErrorCode.ERROR_FORMAT,new String[]{"交易日期"}, "日期:" + strDate);        }    }    /**     * <b>说明: </b>日期转换     * @param intDate     * @param strFormat     * @return     */    public static Date parseDate(int intDate,String strFormat){        return parseDate(String.valueOf(intDate), strFormat);    }    /**     * <b>说明: </b>日期转换     * @param intDate     * @return     */    public static Date parseDate(int intDate){        return parseDate(String.valueOf(intDate));    }    /**     * 日期转换成字符串     * @param date     * @param dateFormat     * @return     */    public static String date2String(Date date,String dateFormat) {        SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);        return formatdate.format(date);    }    /**     * 日期转换成字符串     * @param date     * @param dateFormat     * @return 格式为YYYYMMDD     */    public static String date2String(Date date) {        return date2String(date,DATE_FROMAT);    }    /**     * 日期转换成整数     * @param date     * @param dateFormat     * @return 格式为YYYYMMDD     */    public static int date2Int(Date date) {        String str = date2String(date,DATE_FROMAT);        return Integer.parseInt(str);    }    /***     * <b>说明:</b>      * @param     * @return      * @throws ServiceException     * @author ****     * @since ***     */    public static String getCurrLastDay()    {        return getCurrAfterDay(1);    }    /***     * <b>说明:</b>      * @param     * @return      * @throws ServiceException     * @author ****     * @since ****     */    public static String getCurrAfterDay(int days)    {        Calendar theCa = Calendar.getInstance();        theCa.setTime(new Date());              theCa.add(theCa.DATE, -1*days);        Date date = theCa.getTime();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);        return formatdate.format(date);    }    /**     * 获取交易日期之前的相隔天数的日期     * @param transDate 交易日期     * @param days 天数     * @return     * @author ****     * @since ***     */    public static Integer getTransDateBeforeDay(Integer transDate,int days){        Calendar theCa = Calendar.getInstance();        theCa.setTime(parseDate(transDate));                theCa.add(Calendar.DATE, -1*days);        Date date = theCa.getTime();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);        return Integer.valueOf(formatdate.format(date));    }    /**     * 获取指定日期之后的相隔n年的日期     * @param transDate     * @param years     * @return     * @return Integer     */    public static Integer getDateAfterYear(Integer transDate, int years) {        Calendar theCa = Calendar.getInstance();        theCa.setTime(parseDate(transDate));        theCa.add(Calendar.YEAR, years);        Date date = theCa.getTime();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);        return Integer.valueOf(formatdate.format(date));    }    /**     * 获取交易日期之后的相隔天数的日期     * @param transDate 交易日期     * @param days 天数     * @return     * @author ****     * @since ****     */    public static Integer getTransDateAfterDay(Integer transDate,int days){        Calendar theCa = Calendar.getInstance();        theCa.setTime(parseDate(transDate));                theCa.add(Calendar.DATE, 1*days);        Date date = theCa.getTime();        SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT);        return Integer.valueOf(formatdate.format(date));    }    /**     * 计算两个日期相差的天数     * @param beginDate 【YYYYMMDD】     * @param endDate  【YYYYMMDD】     * @return Integer      * @author ****     * @since ****     */    public static Integer diffDate(Integer beginDate,Integer endDate){                                  Calendar theCa1= Calendar.getInstance();              Calendar theCa2= Calendar.getInstance();              theCa1.setTime(parseDate(beginDate));              theCa2.setTime(parseDate(endDate));                  long between_days=(theCa2.getTimeInMillis()-theCa1.getTimeInMillis())/(1000*3600*24);                      return Integer.parseInt(String.valueOf(between_days));      }}

2.2、字符串处理类

[java] view plain copy
print?
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.security.MessageDigest;  
  5.   
  6. /** 
  7.  * MD5加密工具类 
  8.  */  
  9. public class MD5EncoderUtil {  
  10.     private final static String[] hexDigits = { “0”“1”“2”“3”“4”“5”“6”“7”“8”“9”“a”“b”“c”“d”,  
  11.             ”e”“f” };  
  12.     private static String algorithm = “MD5”;  
  13.   
  14.     public static String encode(String salt, String rawPass) {  
  15.         return encode(rawPass.toLowerCase() + salt);  
  16.     }  
  17.   
  18.     public static String encode(String rawPass) {  
  19.         String result = null;  
  20.         try {  
  21.             MessageDigest md5 = MessageDigest.getInstance(algorithm);  
  22.             // 加密后的字符串  
  23.             result = byteArrayToHexString(md5.digest(rawPass.getBytes(”utf-8”)));  
  24.         } catch (Exception ex) {  
  25.             ex.printStackTrace();  
  26.         }  
  27.         return result;  
  28.     }  
  29.   
  30.     public static String getFileMd5(File file) {  
  31.         FileInputStream fileInputStream = null;  
  32.         try {  
  33.             MessageDigest md5 = MessageDigest.getInstance(algorithm);  
  34.             fileInputStream = new FileInputStream(file);  
  35.             byte[] buffer = new byte[8192];  
  36.             int length;  
  37.             while ((length = fileInputStream.read(buffer)) != -1) {  
  38.                 md5.update(buffer, 0, length);  
  39.             }  
  40.             return byteArrayToHexString(md5.digest());  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.             return null;  
  44.         } finally {  
  45.             if (fileInputStream != null) {  
  46.                 try {  
  47.                     fileInputStream.close();  
  48.                 } catch (IOException e) {  
  49.                     e.printStackTrace();  
  50.                 }  
  51.             }  
  52.   
  53.         }  
  54.   
  55.     }  
  56.   
  57.     public static boolean isPasswordValid(String encPass, String loginName, String rawPass) {  
  58.         String pass1 = encPass;  
  59.         String pass2 = encode(loginName, rawPass);  
  60.         return pass1.toUpperCase().equals(pass2.toUpperCase());  
  61.     }  
  62.   
  63.     /* 
  64.      * 转换字节数组为16进制字串 
  65.      */  
  66.     private static String byteArrayToHexString(byte[] b) {  
  67.         StringBuffer resultSb = new StringBuffer();  
  68.         for (int i = 0; i < b.length; i++) {  
  69.             resultSb.append(byteToHexString(b[i]));  
  70.         }  
  71.         return resultSb.toString();  
  72.     }  
  73.   
  74.     private static String byteToHexString(byte b) {  
  75.         int n = b;  
  76.         if (n < 0)  
  77.             n = 256 + n;  
  78.         int d1 = n / 16;  
  79.         int d2 = n % 16;  
  80.         return hexDigits[d1] + hexDigits[d2];  
  81.     }  
  82. }  
import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.MessageDigest;/** * MD5加密工具类 */public class MD5EncoderUtil {    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",            "e", "f" };    private static String algorithm = "MD5";    public static String encode(String salt, String rawPass) {        return encode(rawPass.toLowerCase() + salt);    }    public static String encode(String rawPass) {        String result = null;        try {            MessageDigest md5 = MessageDigest.getInstance(algorithm);            // 加密后的字符串            result = byteArrayToHexString(md5.digest(rawPass.getBytes("utf-8")));        } catch (Exception ex) {            ex.printStackTrace();        }        return result;    }    public static String getFileMd5(File file) {        FileInputStream fileInputStream = null;        try {            MessageDigest md5 = MessageDigest.getInstance(algorithm);            fileInputStream = new FileInputStream(file);            byte[] buffer = new byte[8192];            int length;            while ((length = fileInputStream.read(buffer)) != -1) {                md5.update(buffer, 0, length);            }            return byteArrayToHexString(md5.digest());        } catch (Exception e) {            e.printStackTrace();            return null;        } finally {            if (fileInputStream != null) {                try {                    fileInputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public static boolean isPasswordValid(String encPass, String loginName, String rawPass) {        String pass1 = encPass;        String pass2 = encode(loginName, rawPass);        return pass1.toUpperCase().equals(pass2.toUpperCase());    }    /*     * 转换字节数组为16进制字串     */    private static String byteArrayToHexString(byte[] b) {        StringBuffer resultSb = new StringBuffer();        for (int i = 0; i < b.length; i++) {            resultSb.append(byteToHexString(b[i]));        }        return resultSb.toString();    }    private static String byteToHexString(byte b) {        int n = b;        if (n < 0)            n = 256 + n;        int d1 = n / 16;        int d2 = n % 16;        return hexDigits[d1] + hexDigits[d2];    }}

2.3、文件处理类

[java] view plain copy
print?
  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5. import java.io.FileWriter;  
  6. import java.io.FilenameFilter;  
  7. import java.io.IOException;  
  8. import java.io.RandomAccessFile;  
  9. import java.io.Reader;  
  10. import java.io.Writer;  
  11. import java.math.BigDecimal;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import org.apache.commons.lang3.StringUtils;  
  15. import org.slf4j.Logger;  
  16. import org.slf4j.LoggerFactory;  
  17. /** 
  18.  *  
  19.  * <b>类说明:文件操作工具类</b> 
  20.  *  
  21.  * <p> 
  22.  * <b>详细描述:</b> 
  23.  *  
  24.  * @author ***** 
  25.  * @since ***** 
  26.  */  
  27. public class FileOperateAssistUtil {  
  28.   
  29.     // 日志记录  
  30.     private static Logger logger = LoggerFactory.getLogger(FileOperateAssistUtil.class);  
  31.   
  32.     /** 
  33.      *  
  34.      * <b>方法说明:</b> 创建文件目录,若路径存在,就不生成 
  35.      *  
  36.      * <p> 
  37.      * <b>详细描述:</b> 
  38.      *  
  39.      * @param 
  40.      * @return 
  41.      * @author ***** 
  42.      * @since ***** 
  43.      */  
  44.     public static void createDocDir(String dirName) {  
  45.         File file = new File(dirName);  
  46.         if (!file.exists()) {  
  47.             file.mkdirs();  
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      *  
  53.      * <b>方法说明:</b> 创建文件目录 
  54.      *  
  55.      * <p> 
  56.      * <b>详细描述:</b> 
  57.      *  
  58.      * @param 
  59.      * @return 
  60.      * @author ***** 
  61.      * @since ***** 
  62.      */  
  63.     public static void isExistsMkDir(String dirName){  
  64.         File file = new File(dirName);  
  65.         if (!file.exists()) {  
  66.             file.mkdirs();  
  67.         }  
  68.     }  
  69.   
  70.     /** 
  71.      * <b>方法说明:</b> 本地,在指定路径生成文件。若文件存在,则删除后重建。 
  72.      *  
  73.      * @param dirName 
  74.      *            本地路径名, 
  75.      * @param file 
  76.      *            文件, 
  77.      * @return List<Object> 
  78.      * @throws ServiceException 
  79.      * @author ***** 
  80.      * @since ***** 
  81.      */  
  82.     public static void creatFileByName(File file){  
  83.         try {  
  84.             if (file.exists()) {  
  85.                 file.delete();  
  86.                 logger.info(”发现同名文件:{},先执行删除,再新建。”, file.getAbsolutePath());  
  87.             }  
  88.             file.createNewFile();  
  89.             logger.info(”创建文件为:{}”, file.getAbsolutePath());  
  90.         }  
  91.         catch (IOException e) {  
  92.             logger.error(”创建{}文件失败”, file.getAbsolutePath(), e);  
  93.            
  94.         }  
  95.     }  
  96.     /** 
  97.      *  
  98.      * <b>说明:</b> 
  99.      * <b>详细描述:创建新文件,若文件存在则删除再创建,若不存在则直接创建</b> 
  100.      * @param   
  101.      * @returnType File 
  102.      * @since ***** 
  103.      * @author ***** 
  104.      */  
  105.     public static File newFile(String fileName) {  
  106.         File file = new File(fileName);  
  107.         creatFileByName(file);  
  108.         return file;  
  109.     }  
  110.     /** 
  111.      *  
  112.      * <b>说明:</b> 
  113.      * <b>详细描述:关闭写入流</b> 
  114.      * @param   
  115.      * @returnType void 
  116.      * @since ***** 
  117.      * @author ***** 
  118.      */  
  119.     public static void closeWriter(Writer writer) {  
  120.         if (writer != null) {  
  121.             try {  
  122.                 writer.close();  
  123.             } catch (IOException e) {  
  124.                 // throw new ServiceException(BatchErrorCode.FILE_CLOSE_EXCEPTION, e);  
  125.                 logger.error(”Close Writer cause Exception:”, e);  
  126.             }  
  127.         }  
  128.     }  
  129.     /** 
  130.      *  
  131.      * <b>说明:</b> 
  132.      * <b>详细描述:关闭写入流</b> 
  133.      * @param   
  134.      * @returnType void 
  135.      * @since ***** 
  136.      * @author ***** 
  137.      */  
  138.     public static void closeReader(Reader reader) {  
  139.         if (reader != null) {  
  140.             try {  
  141.                 reader.close();  
  142.             } catch (IOException e) {   
  143.                 logger.error(”Close reader cause Exception:”, e);  
  144.             }  
  145.         }  
  146.     }  
  147.     /** 
  148.      *  
  149.      * <b>说明:</b> 
  150.      * <b>详细描述:关闭随机读写流</b> 
  151.      * @param   
  152.      * @returnType void 
  153.      * @since ***** 
  154.      * @author ***** 
  155.      */  
  156.     public static void closeRandomAccessFile(RandomAccessFile raf){  
  157.         if(raf != null){  
  158.             try {  
  159.                 raf.close();  
  160.             }catch (IOException e) {  
  161.                 throw new ServiceException(******,e, new String[]{“批量”});  
  162.             }  
  163.         }  
  164.     }  
  165.     public static String getBatchNo(String transDate, Long i) {  
  166.         return transDate + getSerialNo(i);  
  167.     }  
  168.     public static String getFileBatchNo(String date) {  
  169.         if(StringUtils.isBlank(date)){  
  170.             return CtsDateUtil.getCurPcDate();  
  171.         }  
  172.         return date;  
  173.     }  
  174.     public static String getSerialNo(Long i) {  
  175.         return CommUtil.LeftFill(String.valueOf(i), ‘0’3);  
  176.     }  
  177.     public static String getSerialNo(int i) {  
  178.         return CommUtil.LeftFill(String.valueOf(i), ‘0’3);  
  179.     }  
  180.     /** 
  181.      *  
  182.      * <b>方法说明:</b> 创建控制文件 
  183.      *  
  184.      * <p> 
  185.      * <b>详细描述:</b> 
  186.      *  
  187.      * @param 
  188.      * @return 
  189.      * @author ***** 
  190.      * @since***** 
  191.      */  
  192.     public static void createControlFile(File dataFile, Long count) {  
  193.         String controlFileName = dataFile.getAbsolutePath().replace(”.DAT”“.CTL”);  
  194.         File controlFile = null;  
  195.         BufferedWriter bw = null;  
  196.         try {  
  197.             controlFile = new File(controlFileName);  
  198.             if (controlFile.exists()) {  
  199.                 controlFile.delete();  
  200.                 controlFile.createNewFile();  
  201.             }  
  202.             // 获取数据文件MD5  
  203.             String dataFileMd5 = MD5EncoderUtil.getFileMd5(dataFile);  
  204.             StringBuilder controlFileContext = new StringBuilder().append(dataFile.getName()).append(“\t”)  
  205.                     .append(dataFile.length()).append(”\t”).append(count.toString()).append(“\t”)  
  206.                     .append(dataFileMd5 == null ? “” : dataFileMd5);  
  207.             // 将MD5写入控制文件  
  208.             bw = new BufferedWriter(new FileWriter(controlFile, true));  
  209.             bw.write(controlFileContext.toString());  
  210.             bw.flush();  
  211.         }  
  212.         catch (Exception e) {  
  213.             throw new ServiceException(*****, e, new String[]{“控制文件”}, “创建控制文件时发生异常”);  
  214.         }  
  215.         finally {  
  216.             if (bw != null) {  
  217.                 try {  
  218.                     bw.close();  
  219.                 }  
  220.                 catch (IOException e) {  
  221.                     throw new ServiceException(*****, e, new String[]{“控制文件”}, “创建控制文件时发生异常”);  
  222.                 }  
  223.             }  
  224.         }  
  225.     }  
  226.   
  227.     /** 
  228.      *  
  229.      * <b>方法说明:</b> 校验MD5 
  230.      *  
  231.      * <p> 
  232.      * <b>详细描述:</b> 
  233.      *  
  234.      * @param 
  235.      * @return 
  236.      * @author ***** 
  237.      * @since ***** 
  238.      */  
  239.     public static boolean md5Valid(File dataFile) throws ServiceException {  
  240.         String controlFileName = dataFile.getAbsolutePath().replace(”.DAT”“.CTL”);  
  241.         // 获取数据文件的MD5  
  242.         String dataFileMd5 = MD5EncoderUtil.getFileMd5(dataFile);  
  243.         String controlFileMd5 = ”“;  
  244.         BufferedReader reader = null;  
  245.         try {  
  246.   
  247.             reader = new BufferedReader(new FileReader(new File(controlFileName)));  
  248.             String tempString = reader.readLine();  
  249.             // 获取控制文件中的MD5  
  250.             if(StringUtils.isNotBlank(tempString)){  
  251.                 controlFileMd5 = tempString.substring(tempString.lastIndexOf(”\t”) + 1, tempString.length());  
  252.             }else{  
  253.                 throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, new String[]{“文件”}, “校验文件MD5时发生异常”);  
  254.             }  
  255.   
  256.         }  
  257.         catch (Exception e) {  
  258.             logger.error(”校验文件MD5时发生异常”, e);  
  259.             throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, e, new String[]{“文件”}, “校验文件MD5时发生异常”);  
  260.         }  
  261.         finally {  
  262.             if (reader != null) {  
  263.                 try {  
  264.                     reader.close();  
  265.                 }  
  266.                 catch (IOException e) {  
  267.                     throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, e, new String[]{“文件”}, “校验文件MD5时发生异常”);  
  268.                 }  
  269.             }  
  270.         }  
  271.   
  272.         return dataFileMd5.toUpperCase().equals(controlFileMd5.toUpperCase());  
  273.     }  
  274.   
  275.     /** 
  276.      * <b>方法说明:</b> 将字符串拆解按特定标记解析,封装为String[] 
  277.      *  
  278.      * @param String 
  279.      *            tempString 需要拆分的字符串 
  280.      * @param String 
  281.      *            tempString 拆分符号 
  282.      * @param String 
  283.      *            tempString 拆分符号出现次数 
  284.      * @return List<Object> 
  285.      * @throws ServiceException 
  286.      * @author ***** 
  287.      * @since ***** 
  288.      */  
  289.     public static String[] parseStringToStringArray(String tempString, String sign, int num) {  
  290.         List<Object> strlist = new ArrayList<Object>();  
  291.         String[] strList = new String[num + 1];  
  292.         try {  
  293.             int i;  
  294.             for (i = 0; i < num; i++) {  
  295.                 String s1 = tempString.substring(0, tempString.indexOf(sign)).trim();  
  296.                 tempString = tempString.substring(tempString.indexOf(sign) + 1).trim();  
  297.                 strlist.add(s1);  
  298.                 strList[i] = s1;  
  299.                 if (i == num - 1) {  
  300.                     strlist.add(tempString);  
  301.                     strList[i + 1] = tempString;  
  302.                     break;  
  303.                 }  
  304.             }  
  305.         }  
  306.         catch (Exception e) {  
  307.             logger.error(”解析还款清算文件失败”, e);  
  308.             throw new ServiceException(CtsErrorCode.ERROR_PARSE_FILE, e, new String[]{“还款清算”}, “解析还款清算文件失败”);  
  309.         }  
  310.         return strList;  
  311.     }  
  312.   
  313.     /** 
  314.      *  
  315.      * <b>方法说明:</b>格式化时间 
  316.      *  
  317.      * <p> 
  318.      * <b>详细描述:</b> 
  319.      *  
  320.      * @param 
  321.      * @return 
  322.      * @author ***** 
  323.      * @since ***** 
  324.      */  
  325.     public static String foamatTime(String transTime) {  
  326.         return CommUtil.LeftFill(transTime, ‘0’6);  
  327.     }  
  328.   
  329.     /** 
  330.      * <b>方法说明:</b> 上传文件 
  331.      *  
  332.      * @param transDate 
  333.      *            交易日期 
  334.      * @param localPath 
  335.      *            本地路径 
  336.      * @param regName 
  337.      *            文件名前缀 
  338.      * @param remotePath 
  339.      *            远程路径 
  340.      * @return 
  341.      * @throws ServiceException 
  342.      * @author ***** 
  343.      * @since ***** 
  344.      */  
  345.     public static Long uploadFiles(String transDate, String localPath, String regName, String remotePath) {  
  346.   
  347.         SftpClient sftpClient = new SftpClient();  
  348.         try  
  349.         {  
  350.             sftpClient.connect();  
  351.             File[] fileList = listDataAndControlFile(localPath, regName + transDate);  
  352.             List<String> fileNameList  = new ArrayList<String>();  
  353.             Long count = 0L;  
  354.             for (File file : fileList) {  
  355.                 count++;  
  356.                 fileNameList.add(file.getAbsolutePath());  
  357.             }  
  358.             if(count>0)  
  359.                 sftpClient.uploadBatch(remotePath, fileNameList);  
  360.             return count;  
  361.         }finally  
  362.         {  
  363.             sftpClient.disConnect();  
  364.         }  
  365.     }  
  366.   
  367.     public static void uploadFile(String loaclpath, String fileName, String remotePath) {  
  368.         SftpClient sftpClient = new SftpClient();  
  369.         try  
  370.         {  
  371.             File file = new File(loaclpath, fileName);  
  372.             sftpClient.upload(remotePath, file.getAbsolutePath());  
  373.         }finally  
  374.         {  
  375.             sftpClient.disConnect();  
  376.         }  
  377.     }  
  378.       
  379.     public static void uploadFile(String loaclpath, List<String> fileName, String remotePath) {  
  380.         SftpClient sftpClient = new SftpClient();  
  381.         try  
  382.         {  
  383.             List<String> fileNameList  = new ArrayList<String>();  
  384.             Long count = 0L;  
  385.             for (String item : fileName) {  
  386.                 count++;  
  387.                 fileNameList.add(loaclpath+”//”+item);  
  388.             }  
  389.             if(count>0)  
  390.                 sftpClient.uploadBatch(remotePath, fileNameList);  
  391.         }finally  
  392.         {  
  393.             sftpClient.disConnect();  
  394.         }  
  395.     }  
  396.   
  397.     /*** 
  398.      * 按照指定格式分隔字符串 
  399.      * @param tempString 
  400.      * @param splitChar 
  401.      * @return 
  402.      * @return String[] 
  403.      */  
  404.     public static String[] splitString(String tempString,String splitChar) {  
  405.         String[] splits = (tempString.replace(”||”“| | ”) + (“ ”)).split(splitChar);  
  406.         for(int i=0;i<splits.length;i++){  
  407.             if(null == splits[i]){  
  408.                 splits[i]=”“;  
  409.             }  
  410.         }  
  411.         return splits;  
  412.     }  
  413.   
  414.     public static String packProperty(String value) {  
  415.         if (value == null) {  
  416.             return “”;  
  417.         }  
  418.         return value.trim();  
  419.     }  
  420.   
  421.     public static String packProperty(Integer value) {  
  422.         if (value == null) {  
  423.             return “”;  
  424.         }  
  425.         return value.toString();  
  426.     }  
  427.   
  428.     public static String packProperty(BigDecimal value) {  
  429.         if (value == null) {  
  430.             return “”;  
  431.         }  
  432.         return value.toString();  
  433.     }  
  434.   
  435.     /** 
  436.      *  
  437.      * <b> 方法说明:</b><BR> 
  438.      * 获取本地目录下过滤后的数据文件列表 
  439.      *  
  440.      * @param localPath 要查询的数据文件的路径 
  441.      * @param namePrefix 要过滤出来的数据文件前缀 
  442.      * @return File[] 文件列表 
  443.      * @author ***** 
  444.      */  
  445.     public static File[] listDataFile(String localPath, final String namePrefix) {  
  446.         FilenameFilter nameFilter = new FilenameFilter() {  
  447.   
  448.             @Override  
  449.             public boolean accept(File dir, String fileName) {  
  450.                 return fileName.startsWith(namePrefix) && (fileName.endsWith(“.DAT”));  
  451.             }  
  452.         };  
  453.   
  454.         File[] fileList = new File(localPath).listFiles(nameFilter);  
  455.         return fileList == null ? new File[0] : fileList;  
  456.     }  
  457.   
  458.     /** 
  459.      *  
  460.      * <b>方法说明:</b> 获取本地目录下过滤后的数据文件和控制文件列表 
  461.      *  
  462.      * @param 
  463.      * @return 
  464.      * @author ***** 
  465.      * @since ***** 
  466.      */  
  467.     public static File[] listDataAndControlFile(String localPath, String reg) {  
  468.         final String regName = reg;  
  469.         logger.debug(”localPath:”+localPath+“,reg:”+reg);  
  470.         FilenameFilter nameFilter = new FilenameFilter() {  
  471.   
  472.             @Override  
  473.             public boolean accept(File dir, String fileName) {  
  474.                 return fileName.indexOf(regName) >= 0 && (fileName.endsWith(“.DAT”) || fileName.endsWith(“.CTL”));  
  475.             }  
  476.         };  
  477.   
  478.         File[] fileList = new File(localPath).listFiles(nameFilter);  
  479.         return fileList;  
  480.     }  
  481.     public static File[] deleteFilesFromDir(String localPath, String reg) {  
  482.         File[] oldFileList = FileOperateAssistUtil.listDataAndControlFile(localPath,reg);  
  483.         for (File file : oldFileList) {  
  484.             file.delete();  
  485.         }  
  486.         return oldFileList;  
  487.     }  
  488.     public static String getBatchNoByFile(File file) {  
  489.         String fileName = file.getName();  
  490.         String str = fileName.substring(fileName.lastIndexOf(”_”) + 1, fileName.lastIndexOf(“.”));  
  491.         return str.length() <= 3 ? str : “001”;  
  492.     }  
  493.   
  494. }  
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.FilenameFilter;import java.io.IOException;import java.io.RandomAccessFile;import java.io.Reader;import java.io.Writer;import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** *  * <b>类说明:文件操作工具类</b> *  * <p> * <b>详细描述:</b> *  * @author ***** * @since ***** */public class FileOperateAssistUtil {    // 日志记录    private static Logger logger = LoggerFactory.getLogger(FileOperateAssistUtil.class);    /**     *      * <b>方法说明:</b> 创建文件目录,若路径存在,就不生成     *      * <p>     * <b>详细描述:</b>     *      * @param     * @return     * @author *****     * @since *****     */    public static void createDocDir(String dirName) {        File file = new File(dirName);        if (!file.exists()) {            file.mkdirs();        }    }    /**     *      * <b>方法说明:</b> 创建文件目录     *      * <p>     * <b>详细描述:</b>     *      * @param     * @return     * @author *****     * @since *****     */    public static void isExistsMkDir(String dirName){        File file = new File(dirName);        if (!file.exists()) {            file.mkdirs();        }    }    /**     * <b>方法说明:</b> 本地,在指定路径生成文件。若文件存在,则删除后重建。     *      * @param dirName     *            本地路径名,     * @param file     *            文件,     * @return List<Object>     * @throws ServiceException     * @author *****     * @since *****     */    public static void creatFileByName(File file){        try {            if (file.exists()) {                file.delete();                logger.info("发现同名文件:{},先执行删除,再新建。", file.getAbsolutePath());            }            file.createNewFile();            logger.info("创建文件为:{}", file.getAbsolutePath());        }        catch (IOException e) {            logger.error("创建{}文件失败", file.getAbsolutePath(), e);        }    }    /**     *      * <b>说明:</b>     * <b>详细描述:创建新文件,若文件存在则删除再创建,若不存在则直接创建</b>     * @param       * @returnType File     * @since *****     * @author *****     */    public static File newFile(String fileName) {        File file = new File(fileName);        creatFileByName(file);        return file;    }    /**     *      * <b>说明:</b>     * <b>详细描述:关闭写入流</b>     * @param       * @returnType void     * @since *****     * @author *****     */    public static void closeWriter(Writer writer) {        if (writer != null) {            try {                writer.close();            } catch (IOException e) {                // throw new ServiceException(BatchErrorCode.FILE_CLOSE_EXCEPTION, e);                logger.error("Close Writer cause Exception:", e);            }        }    }    /**     *      * <b>说明:</b>     * <b>详细描述:关闭写入流</b>     * @param       * @returnType void     * @since *****     * @author *****     */    public static void closeReader(Reader reader) {        if (reader != null) {            try {                reader.close();            } catch (IOException e) {                 logger.error("Close reader cause Exception:", e);            }        }    }    /**     *      * <b>说明:</b>     * <b>详细描述:关闭随机读写流</b>     * @param       * @returnType void     * @since *****     * @author *****     */    public static void closeRandomAccessFile(RandomAccessFile raf){        if(raf != null){            try {                raf.close();            }catch (IOException e) {                throw new ServiceException(******,e, new String[]{"批量"});            }        }    }    public static String getBatchNo(String transDate, Long i) {        return transDate + getSerialNo(i);    }    public static String getFileBatchNo(String date) {        if(StringUtils.isBlank(date)){            return CtsDateUtil.getCurPcDate();        }        return date;    }    public static String getSerialNo(Long i) {        return CommUtil.LeftFill(String.valueOf(i), '0', 3);    }    public static String getSerialNo(int i) {        return CommUtil.LeftFill(String.valueOf(i), '0', 3);    }    /**     *      * <b>方法说明:</b> 创建控制文件     *      * <p>     * <b>详细描述:</b>     *      * @param     * @return     * @author *****     * @since*****     */    public static void createControlFile(File dataFile, Long count) {        String controlFileName = dataFile.getAbsolutePath().replace(".DAT", ".CTL");        File controlFile = null;        BufferedWriter bw = null;        try {            controlFile = new File(controlFileName);            if (controlFile.exists()) {                controlFile.delete();                controlFile.createNewFile();            }            // 获取数据文件MD5            String dataFileMd5 = MD5EncoderUtil.getFileMd5(dataFile);            StringBuilder controlFileContext = new StringBuilder().append(dataFile.getName()).append("\t")                    .append(dataFile.length()).append("\t").append(count.toString()).append("\t")                    .append(dataFileMd5 == null ? "" : dataFileMd5);            // 将MD5写入控制文件            bw = new BufferedWriter(new FileWriter(controlFile, true));            bw.write(controlFileContext.toString());            bw.flush();        }        catch (Exception e) {            throw new ServiceException(*****, e, new String[]{"控制文件"}, "创建控制文件时发生异常");        }        finally {            if (bw != null) {                try {                    bw.close();                }                catch (IOException e) {                    throw new ServiceException(*****, e, new String[]{"控制文件"}, "创建控制文件时发生异常");                }            }        }    }    /**     *      * <b>方法说明:</b> 校验MD5     *      * <p>     * <b>详细描述:</b>     *      * @param     * @return     * @author *****     * @since *****     */    public static boolean md5Valid(File dataFile) throws ServiceException {        String controlFileName = dataFile.getAbsolutePath().replace(".DAT", ".CTL");        // 获取数据文件的MD5        String dataFileMd5 = MD5EncoderUtil.getFileMd5(dataFile);        String controlFileMd5 = "";        BufferedReader reader = null;        try {            reader = new BufferedReader(new FileReader(new File(controlFileName)));            String tempString = reader.readLine();            // 获取控制文件中的MD5            if(StringUtils.isNotBlank(tempString)){                controlFileMd5 = tempString.substring(tempString.lastIndexOf("\t") + 1, tempString.length());            }else{                throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, new String[]{"文件"}, "校验文件MD5时发生异常");            }        }        catch (Exception e) {            logger.error("校验文件MD5时发生异常", e);            throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, e, new String[]{"文件"}, "校验文件MD5时发生异常");        }        finally {            if (reader != null) {                try {                    reader.close();                }                catch (IOException e) {                    throw new ServiceException(CtsErrorCode.ERROR_VALIDATE_MD5, e, new String[]{"文件"}, "校验文件MD5时发生异常");                }            }        }        return dataFileMd5.toUpperCase().equals(controlFileMd5.toUpperCase());    }    /**     * <b>方法说明:</b> 将字符串拆解按特定标记解析,封装为String[]     *      * @param String     *            tempString 需要拆分的字符串     * @param String     *            tempString 拆分符号     * @param String     *            tempString 拆分符号出现次数     * @return List<Object>     * @throws ServiceException     * @author *****     * @since *****     */    public static String[] parseStringToStringArray(String tempString, String sign, int num) {        List<Object> strlist = new ArrayList<Object>();        String[] strList = new String[num + 1];        try {            int i;            for (i = 0; i < num; i++) {                String s1 = tempString.substring(0, tempString.indexOf(sign)).trim();                tempString = tempString.substring(tempString.indexOf(sign) + 1).trim();                strlist.add(s1);                strList[i] = s1;                if (i == num - 1) {                    strlist.add(tempString);                    strList[i + 1] = tempString;                    break;                }            }        }        catch (Exception e) {            logger.error("解析还款清算文件失败", e);            throw new ServiceException(CtsErrorCode.ERROR_PARSE_FILE, e, new String[]{"还款清算"}, "解析还款清算文件失败");        }        return strList;    }    /**     *      * <b>方法说明:</b>格式化时间     *      * <p>     * <b>详细描述:</b>     *      * @param     * @return     * @author *****     * @since *****     */    public static String foamatTime(String transTime) {        return CommUtil.LeftFill(transTime, '0', 6);    }    /**     * <b>方法说明:</b> 上传文件     *      * @param transDate     *            交易日期     * @param localPath     *            本地路径     * @param regName     *            文件名前缀     * @param remotePath     *            远程路径     * @return     * @throws ServiceException     * @author *****     * @since *****     */    public static Long uploadFiles(String transDate, String localPath, String regName, String remotePath) {        SftpClient sftpClient = new SftpClient();        try        {            sftpClient.connect();            File[] fileList = listDataAndControlFile(localPath, regName + transDate);            List<String> fileNameList  = new ArrayList<String>();            Long count = 0L;            for (File file : fileList) {                count++;                fileNameList.add(file.getAbsolutePath());            }            if(count>0)                sftpClient.uploadBatch(remotePath, fileNameList);            return count;        }finally        {            sftpClient.disConnect();        }    }    public static void uploadFile(String loaclpath, String fileName, String remotePath) {        SftpClient sftpClient = new SftpClient();        try        {            File file = new File(loaclpath, fileName);            sftpClient.upload(remotePath, file.getAbsolutePath());        }finally        {            sftpClient.disConnect();        }    }    public static void uploadFile(String loaclpath, List<String> fileName, String remotePath) {        SftpClient sftpClient = new SftpClient();        try        {            List<String> fileNameList  = new ArrayList<String>();            Long count = 0L;            for (String item : fileName) {                count++;                fileNameList.add(loaclpath+"//"+item);            }            if(count>0)                sftpClient.uploadBatch(remotePath, fileNameList);        }finally        {            sftpClient.disConnect();        }    }    /***     * 按照指定格式分隔字符串     * @param tempString     * @param splitChar     * @return     * @return String[]     */    public static String[] splitString(String tempString,String splitChar) {        String[] splits = (tempString.replace("||", "| | ") + (" ")).split(splitChar);        for(int i=0;i<splits.length;i++){            if(null == splits[i]){                splits[i]="";            }        }        return splits;    }    public static String packProperty(String value) {        if (value == null) {            return "";        }        return value.trim();    }    public static String packProperty(Integer value) {        if (value == null) {            return "";        }        return value.toString();    }    public static String packProperty(BigDecimal value) {        if (value == null) {            return "";        }        return value.toString();    }    /**     *      * <b> 方法说明:</b><BR>     * 获取本地目录下过滤后的数据文件列表     *      * @param localPath 要查询的数据文件的路径     * @param namePrefix 要过滤出来的数据文件前缀     * @return File[] 文件列表     * @author *****     */    public static File[] listDataFile(String localPath, final String namePrefix) {        FilenameFilter nameFilter = new FilenameFilter() {            @Override            public boolean accept(File dir, String fileName) {                return fileName.startsWith(namePrefix) && (fileName.endsWith(".DAT"));            }        };        File[] fileList = new File(localPath).listFiles(nameFilter);        return fileList == null ? new File[0] : fileList;    }    /**     *      * <b>方法说明:</b> 获取本地目录下过滤后的数据文件和控制文件列表     *      * @param     * @return     * @author *****     * @since *****     */    public static File[] listDataAndControlFile(String localPath, String reg) {        final String regName = reg;        logger.debug("localPath:"+localPath+",reg:"+reg);        FilenameFilter nameFilter = new FilenameFilter() {            @Override            public boolean accept(File dir, String fileName) {                return fileName.indexOf(regName) >= 0 && (fileName.endsWith(".DAT") || fileName.endsWith(".CTL"));            }        };        File[] fileList = new File(localPath).listFiles(nameFilter);        return fileList;    }    public static File[] deleteFilesFromDir(String localPath, String reg) {        File[] oldFileList = FileOperateAssistUtil.listDataAndControlFile(localPath,reg);        for (File file : oldFileList) {            file.delete();        }        return oldFileList;    }    public static String getBatchNoByFile(File file) {        String fileName = file.getName();        String str = fileName.substring(fileName.lastIndexOf("_") + 1, fileName.lastIndexOf("."));        return str.length() <= 3 ? str : "001";    }}

2.4、DAO基类

[java] view plain copy
print?
  1. package com.lz.ctsframework.core.support;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.Param;  
  6. /** 
  7.  *  
  8.  * <b>类说明:</b>dao基类 
  9.  *  
  10.  * <p> 
  11.  * <b>详细描述:</b> 
  12.  *  
  13.  * @author ** 
  14.  * @since *** 
  15.  */  
  16. public interface IBaseDao<T,E,K> {  
  17.       
  18.     int countByCriteria(E criteria);  
  19.   
  20.     int deleteByCriteria(E criteria);  
  21.   
  22.     int deleteByPrimaryKey(K key);  
  23.   
  24.     int insert(T entity);  
  25.   
  26.     int insertSelective(T entity);  
  27.   
  28.     List<T> selectByCriteria(E criteria);  
  29.   
  30.     T selectByPrimaryKey(K key);  
  31.   
  32.     int updateByCriteriaSelective(@Param(“record”) T entity, @Param(“example”) E criteria);  
  33.   
  34.     //int updateByCriteria(@Param(“record”) T entity, @Param(“example”) E criteria);  
  35.   
  36.     int updateByPrimaryKeySelective(T entity);  
  37.   
  38.     //int updateByPrimaryKey(T entity);  
  39. }  
package com.lz.ctsframework.core.support;import java.util.List;import org.apache.ibatis.annotations.Param;/** *  * <b>类说明:</b>dao基类 *  * <p> * <b>详细描述:</b> *  * @author ** * @since *** */public interface IBaseDao<T,E,K> {    int countByCriteria(E criteria);    int deleteByCriteria(E criteria);    int deleteByPrimaryKey(K key);    int insert(T entity);    int insertSelective(T entity);    List<T> selectByCriteria(E criteria);    T selectByPrimaryKey(K key);    int updateByCriteriaSelective(@Param("record") T entity, @Param("example") E criteria);    //int updateByCriteria(@Param("record") T entity, @Param("example") E criteria);    int updateByPrimaryKeySelective(T entity);    //int updateByPrimaryKey(T entity);}

2.5、异常抛出类

[java] view plain copy
print?
  1. package com.lz.ctsframework.core.support;  
  2.   
  3. import java.text.MessageFormat;  
  4.   
  5. /** 
  6.  *  
  7.  * <b>类说明:</b>Service层统一抛出的异常 
  8.  *  
  9.  * <p> 
  10.  * <b>详细描述:</b> 
  11.  *  
  12.  * @author ***** 
  13.  * @since ***** 
  14.  */  
  15. public class ServiceException extends RuntimeException {      
  16.   
  17.     private static final long serialVersionUID = 6514891174875747380L;  
  18.   
  19.   
  20.     /** 异常错误码 **/  
  21.     private String code;  
  22.   
  23.     /** 异常描述 **/  
  24.     private String msg;   
  25.     /** 扩展异常描述(包括msg) **/  
  26.     private String extMsg;  
  27.   
  28.     /** 
  29.      * ServiceException构造方法,有format字符组 
  30.      * @param errorCode 错误码 
  31.      * @param param     format字符组 
  32.      * @param extMsg    扩展信息,给出具体的错误值信息等 
  33.      */  
  34.     public ServiceException(ErrorCode errorCode,String param[],String … extMsg) {  
  35.         super(null==errorCode ? “” : errorCode.getCode());  
  36.         init(errorCode, param,extMsg);  
  37.     }  
  38.   
  39.     /** 
  40.      * ServiceException构造方法,有format字符组 
  41.      * @param errCode 
  42.      * @param paramsList 
  43.      */  
  44.     public ServiceException(ErrorCode errCode, Object… paramsList) {  
  45.         Object[] params = null;  
  46.         if ((paramsList != null) && (paramsList.length > 0)   
  47.                 && ((paramsList[(paramsList.length - 1)] instanceof Throwable)))   
  48.         {  
  49.             Object[] newParam = new Object[paramsList.length - 1];  
  50.             System.arraycopy(paramsList, 0, newParam, 0, newParam.length);  
  51.             params = newParam;  
  52.             super.initCause((Throwable)paramsList[(paramsList.length - 1)]);  
  53.         }  
  54.         else {  
  55.             params = paramsList;  
  56.             super.initCause(null);  
  57.         }  
  58.   
  59.         this.code = null==errCode ? “” : errCode.getCode();  
  60.         this.msg = null==errCode ? “” :  MessageFormat.format(errCode.getMsg(),params);    
  61.         this.extMsg = this.msg;  
  62.     }  
  63.   
  64.     private void init(ErrorCode errorCode, String param[], String… extMsg) {  
  65.         this.code = null==errorCode ? “” : errorCode.getCode();  
  66.         this.msg = null==errorCode ? “” : MessageFormat.format(errorCode.getMsg(),param);  
  67.         StringBuilder builder = new StringBuilder(100);  
  68.         builder.append(this.msg);  
  69.         if(null != extMsg){  
  70.             for(String ext : extMsg ){  
  71.                 builder.append(”[“).append(ext).append(“]”);  
  72.             }  
  73.         }  
  74.         this.extMsg = builder.toString();  
  75.     }  
  76.   
  77.     /** 
  78.      *  
  79.      * @param code  错误码 
  80.      * @param msg 描述信息 
  81.      */  
  82.     public ServiceException(String code, String msg) {  
  83.         super(code+“:”+msg);  
  84.         this.code = code;  
  85.         this.msg = msg;  
  86.     }  
  87.   
  88.     /** 
  89.      * 带Exception的构造方法,传format字符数组 
  90.      * @param errorCode 错误码基类 
  91.      * @param e  异常 
  92.      * @param extMsg    扩展信息,给出具体的错误值信息等 
  93.      */  
  94.     public ServiceException(ErrorCode errorCode, Throwable e,String param[] , String …extMsg ) {  
  95.         super(null==errorCode ? “” : errorCode.getCode(), e);  
  96.         init(errorCode, param, extMsg);  
  97.     }  
  98.   
  99.     /** 
  100.      *  
  101.      * @param code 错误码 
  102.      * @param msg 描述信息 
  103.      * @param e  异常 
  104.      */  
  105.     /*public ServiceException(String code, String msg,Throwable e) { 
  106.         super(code+”:”+msg, e); 
  107.         this.code = code; 
  108.         this.msg = msg;  
  109.     }*/  
  110.   
  111.     /** 
  112.      *  
  113.      *  
  114.      * 方法说明:异常错误码 
  115.      *  
  116.      * @return 
  117.      */  
  118.     public String getCode() {  
  119.         return code;  
  120.     }  
  121.   
  122.     /** 
  123.      *  
  124.      *  
  125.      * 方法说明:异常描述信息 
  126.      *  
  127.      * @return 
  128.      */  
  129.     public String getMsg() {  
  130.         return msg;  
  131.     }  
  132.   
  133.     public String getExtMsg() {  
  134.         return extMsg;  
  135.     }  
  136.   
  137.     @Override  
  138.     public String getMessage() {          
  139.         return super.getMessage() + “,”+extMsg;  
  140.     }     
  141.   
  142.     public static void main(String[] args) {  
  143.   
  144.     }  
  145.   
  146. }  
package com.lz.ctsframework.core.support;import java.text.MessageFormat;/** *  * <b>类说明:</b>Service层统一抛出的异常 *  * <p> * <b>详细描述:</b> *  * @author ***** * @since ***** */public class ServiceException extends RuntimeException {        private static final long serialVersionUID = 6514891174875747380L;    /** 异常错误码 **/    private String code;    /** 异常描述 **/    private String msg;     /** 扩展异常描述(包括msg) **/    private String extMsg;    /**     * ServiceException构造方法,有format字符组     * @param errorCode 错误码     * @param param     format字符组     * @param extMsg    扩展信息,给出具体的错误值信息等     */    public ServiceException(ErrorCode errorCode,String param[],String ... extMsg) {        super(null==errorCode ? "" : errorCode.getCode());        init(errorCode, param,extMsg);    }    /**     * ServiceException构造方法,有format字符组     * @param errCode     * @param paramsList     */    public ServiceException(ErrorCode errCode, Object... paramsList) {        Object[] params = null;        if ((paramsList != null) && (paramsList.length > 0)                 && ((paramsList[(paramsList.length - 1)] instanceof Throwable)))         {            Object[] newParam = new Object[paramsList.length - 1];            System.arraycopy(paramsList, 0, newParam, 0, newParam.length);            params = newParam;            super.initCause((Throwable)paramsList[(paramsList.length - 1)]);        }        else {            params = paramsList;            super.initCause(null);        }        this.code = null==errCode ? "" : errCode.getCode();        this.msg = null==errCode ? "" :  MessageFormat.format(errCode.getMsg(),params);          this.extMsg = this.msg;    }    private void init(ErrorCode errorCode, String param[], String... extMsg) {        this.code = null==errorCode ? "" : errorCode.getCode();        this.msg = null==errorCode ? "" : MessageFormat.format(errorCode.getMsg(),param);        StringBuilder builder = new StringBuilder(100);        builder.append(this.msg);        if(null != extMsg){            for(String ext : extMsg ){                builder.append("[").append(ext).append("]");            }        }        this.extMsg = builder.toString();    }    /**     *      * @param code  错误码     * @param msg 描述信息     */    public ServiceException(String code, String msg) {        super(code+":"+msg);        this.code = code;        this.msg = msg;    }    /**     * 带Exception的构造方法,传format字符数组     * @param errorCode 错误码基类     * @param e  异常     * @param extMsg    扩展信息,给出具体的错误值信息等     */    public ServiceException(ErrorCode errorCode, Throwable e,String param[] , String ...extMsg ) {        super(null==errorCode ? "" : errorCode.getCode(), e);        init(errorCode, param, extMsg);    }    /**     *      * @param code 错误码     * @param msg 描述信息     * @param e  异常     */    /*public ServiceException(String code, String msg,Throwable e) {        super(code+":"+msg, e);        this.code = code;        this.msg = msg;     }*/    /**     *      *      * 方法说明:异常错误码     *      * @return     */    public String getCode() {        return code;    }    /**     *      *      * 方法说明:异常描述信息     *      * @return     */    public String getMsg() {        return msg;    }    public String getExtMsg() {        return extMsg;    }    @Override    public String getMessage() {                return super.getMessage() + ","+extMsg;    }       public static void main(String[] args) {    }}

2.6 JSON处理类

[java] view plain copy
print?
  1. import java.io.IOException;  
  2. import java.io.StringReader;  
  3. import java.io.StringWriter;  
  4. import java.util.ArrayList;  
  5. import java.util.Collection;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import com.fasterxml.jackson.core.JsonFactory;  
  11. import com.fasterxml.jackson.core.JsonGenerator;  
  12. import com.fasterxml.jackson.core.JsonParseException;  
  13. import com.fasterxml.jackson.core.JsonParser;  
  14. import com.fasterxml.jackson.databind.DeserializationFeature;  
  15. import com.fasterxml.jackson.databind.ObjectMapper;  
  16. /** 
  17.  *  
  18.  * <b>类说明:</b>Jackson工具类 
  19.  *  
  20.  * <p> 
  21.  * <b>详细描述:</b> 
  22.  *  
  23.  * @author **** 
  24.  * @since *** 
  25.  */  
  26. public class JacksonUtil {  
  27.     private static final ObjectMapper MAPPER = new ObjectMapper();  
  28.   
  29.     static {  
  30.         MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
  31.     }  
  32.   
  33.     private static final JsonFactory JSONFACTORY = new JsonFactory();  
  34.   
  35.     /** 
  36.      * 转换Java Bean 为 json 
  37.      */  
  38.     public static String beanToJson(Object o) throws JsonParseException {  
  39.         StringWriter sw = new StringWriter();  
  40.         JsonGenerator jsonGenerator = null;  
  41.   
  42.         try {  
  43.             jsonGenerator = JSONFACTORY.createJsonGenerator(sw);  
  44.             MAPPER.writeValue(jsonGenerator, o);  
  45.             return sw.toString();  
  46.   
  47.         } catch (Exception e) {  
  48.             throw new RuntimeException(e+“转换Java Bean 为 json错误”);  
  49.   
  50.         } finally {  
  51.             if (jsonGenerator != null) {  
  52.                 try {  
  53.                     jsonGenerator.close();  
  54.                 } catch (Exception e) {  
  55.                     throw new RuntimeException(e+“转换Java Bean 为 json错误”);  
  56.                 }  
  57.             }  
  58.         }  
  59.     }  
  60.   
  61.     /** 
  62.      * json 转 javabean 
  63.      * 
  64.      * @param json 
  65.      * @return 
  66.      */  
  67.     @SuppressWarnings({ “unchecked”“rawtypes” })  
  68.     public static Object jsonToBean(String json, Class clazz) throws JsonParseException {  
  69.         try {  
  70. //          MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
  71.               
  72.             return MAPPER.readValue(json, clazz);  
  73.         } catch (Exception e) {  
  74.             throw new RuntimeException(e+“json 转 javabean错误”);  
  75.         }  
  76.     }  
  77.   
  78.     /** 
  79.      * 转换Java Bean 为 HashMap 
  80.      */  
  81.     @SuppressWarnings(“unchecked”)  
  82.     public static Map<String, Object> beanToMap(Object o) throws JsonParseException {  
  83.         try {  
  84.             return MAPPER.readValue(beanToJson(o), HashMap.class);  
  85.         } catch (Exception e) {  
  86.             throw new RuntimeException(e+“转换Java Bean 为 HashMap错误”);  
  87.         }  
  88.     }  
  89.   
  90.     /** 
  91.      * 转换Json String 为 HashMap 
  92.      */  
  93.     @SuppressWarnings(“unchecked”)  
  94.     public static Map<String, Object> jsonToMap(String json, boolean collToString) throws JsonParseException {  
  95.         Map<String, Object> map = null;  
  96.         try {  
  97.             map = MAPPER.readValue(json, HashMap.class);  
  98.         } catch (IOException e) {  
  99.             throw new RuntimeException(e+“转换Java Bean 为 HashMap错误”);  
  100.         }  
  101.         if (collToString) {  
  102.             for (Map.Entry<String, Object> entry : map.entrySet()) {  
  103.                 if (entry.getValue() instanceof Collection || entry.getValue() instanceof Map) {  
  104.                     entry.setValue(beanToJson(entry.getValue()));  
  105.                 }  
  106.             }  
  107.         }  
  108.         return map;  
  109.   
  110.     }  
  111.   
  112.     /** 
  113.      * List 转换成json 
  114.      * 
  115.      * @param list 
  116.      * @return 
  117.      */  
  118.     public static String listToJson(List<Map<String, String>> list) throws JsonParseException {  
  119.         JsonGenerator jsonGenerator = null;  
  120.         StringWriter sw = new StringWriter();  
  121.         try {  
  122.             jsonGenerator = JSONFACTORY.createJsonGenerator(sw);  
  123.             new ObjectMapper().writeValue(jsonGenerator, list);  
  124.             jsonGenerator.flush();  
  125.             return sw.toString();  
  126.         } catch (Exception e) {  
  127.             throw new RuntimeException(e+“List 转换成json错误”);  
  128.         } finally {  
  129.             if (jsonGenerator != null) {  
  130.                 try {  
  131.                     jsonGenerator.flush();  
  132.                     jsonGenerator.close();  
  133.                 } catch (Exception e) {  
  134.                     throw new RuntimeException(e+“List 转换成json错误”);  
  135.                 }  
  136.             }  
  137.         }  
  138.     }  
  139.   
  140.     /** 
  141.      * json 转List 
  142.      * 
  143.      * @param json 
  144.      * @return 
  145.      */  
  146.     @SuppressWarnings(“unchecked”)  
  147.     public static List<Map<String, String>> jsonToList(String json) throws JsonParseException {  
  148.         try {  
  149.             if (json != null && !“”.equals(json.trim())) {  
  150.                 JsonParser jsonParse = JSONFACTORY.createJsonParser(new StringReader(json));  
  151.   
  152.                 return (List<Map<String, String>>) new ObjectMapper().readValue(jsonParse, ArrayList.class);  
  153.             } else {  
  154.                 throw new RuntimeException(“json 转List错误”);  
  155.             }  
  156.         } catch (Exception e) {  
  157.             throw new RuntimeException(e+“json 转List错误”);  
  158.         }  
  159.     }  
  160. }  
import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.List;import java.util.Map;import com.fasterxml.jackson.core.JsonFactory;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;/** *  * <b>类说明:</b>Jackson工具类 *  * <p> * <b>详细描述:</b> *  * @author **** * @since *** */public class JacksonUtil {    private static final ObjectMapper MAPPER = new ObjectMapper();    static {        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    }    private static final JsonFactory JSONFACTORY = new JsonFactory();    /**     * 转换Java Bean 为 json     */    public static String beanToJson(Object o) throws JsonParseException {        StringWriter sw = new StringWriter();        JsonGenerator jsonGenerator = null;        try {            jsonGenerator = JSONFACTORY.createJsonGenerator(sw);            MAPPER.writeValue(jsonGenerator, o);            return sw.toString();        } catch (Exception e) {            throw new RuntimeException(e+"转换Java Bean 为 json错误");        } finally {            if (jsonGenerator != null) {                try {                    jsonGenerator.close();                } catch (Exception e) {                    throw new RuntimeException(e+"转换Java Bean 为 json错误");                }            }        }    }    /**     * json 转 javabean     *     * @param json     * @return     */    @SuppressWarnings({ "unchecked", "rawtypes" })    public static Object jsonToBean(String json, Class clazz) throws JsonParseException {        try {//          MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);            return MAPPER.readValue(json, clazz);        } catch (Exception e) {            throw new RuntimeException(e+"json 转 javabean错误");        }    }    /**     * 转换Java Bean 为 HashMap     */    @SuppressWarnings("unchecked")    public static Map<String, Object> beanToMap(Object o) throws JsonParseException {        try {            return MAPPER.readValue(beanToJson(o), HashMap.class);        } catch (Exception e) {            throw new RuntimeException(e+"转换Java Bean 为 HashMap错误");        }    }    /**     * 转换Json String 为 HashMap     */    @SuppressWarnings("unchecked")    public static Map<String, Object> jsonToMap(String json, boolean collToString) throws JsonParseException {        Map<String, Object> map = null;        try {            map = MAPPER.readValue(json, HashMap.class);        } catch (IOException e) {            throw new RuntimeException(e+"转换Java Bean 为 HashMap错误");        }        if (collToString) {            for (Map.Entry<String, Object> entry : map.entrySet()) {                if (entry.getValue() instanceof Collection || entry.getValue() instanceof Map) {                    entry.setValue(beanToJson(entry.getValue()));                }            }        }        return map;    }    /**     * List 转换成json     *     * @param list     * @return     */    public static String listToJson(List<Map<String, String>> list) throws JsonParseException {        JsonGenerator jsonGenerator = null;        StringWriter sw = new StringWriter();        try {            jsonGenerator = JSONFACTORY.createJsonGenerator(sw);            new ObjectMapper().writeValue(jsonGenerator, list);            jsonGenerator.flush();            return sw.toString();        } catch (Exception e) {            throw new RuntimeException(e+"List 转换成json错误");        } finally {            if (jsonGenerator != null) {                try {                    jsonGenerator.flush();                    jsonGenerator.close();                } catch (Exception e) {                    throw new RuntimeException(e+"List 转换成json错误");                }            }        }    }    /**     * json 转List     *     * @param json     * @return     */    @SuppressWarnings("unchecked")    public static List<Map<String, String>> jsonToList(String json) throws JsonParseException {        try {            if (json != null && !"".equals(json.trim())) {                JsonParser jsonParse = JSONFACTORY.createJsonParser(new StringReader(json));                return (List<Map<String, String>>) new ObjectMapper().readValue(jsonParse, ArrayList.class);            } else {                throw new RuntimeException("json 转List错误");            }        } catch (Exception e) {            throw new RuntimeException(e+"json 转List错误");        }    }}

四、常用框架

4.1、日志打印-快速定位错

       或许有人看到这里会认为日志不重要,因为大家平时用得最多的估计就是System.out.prinln()之类的,这种方法对于小程序是没问题。但是,对于一个完整的项目,有开发、有测试的。一方面,你如果开发过程中,每个地方都要手动的输出这些语句,岂不是很麻烦。特别是使用Mybatis或Hibernate之类的框架,你想看看程序跑的时候,调用的SQL语句。没有日志就很难做到。另一方面,项目如果部署在服务器之上,测试人员在进行测试时,就无法使用System.out.之类的语句来看输出了。这时,统一的把程序运行的日志输出到一个文件中去。然后通过一些linux的命令,就可以快速找到报错的信息是什么。这里兴趣的同学可以看我写的:Log4j详细使用教程

一个典型的Log4j结构:

在小的项目中,可以日志的作用没那么明显,但是把日志和框架结合起来用就很常见,比如和Spring/mybatis/SprinMVC/Tomcat等的结合,打印出来的日志可以如下,这里日志的格式可以自己来控制,以及日志输入的等级。下面是控制台的输出日志

下面是输出到外部的日志文件


4.2、Maven-jar的自动管理

     Maven还没出现之前,每次新建一个Java或web项目,都得往编程路径里放很多Jar包。传统引入jar的方式是将其放入web-inf->lib目录里面,无形中增大了项目,而且jar不能统一进行管理。使用Maven的好处之一就是通过配置POM.XML文件自动下载jar包,并且通过中心库统一进行管理、版本的控制等。

一个典型的maven的web项目结构:

使用Maven的一些好处

       1. Maven的库是由开源组织维护,不需要我们再花精力去管第三方库,即使自己维护,也比较方便。
       2. Maven对jar包的版本管理有工具上的支持,比如将Release版本和Snapshot版本区分开,有利于SCM管理。
       3. Maven是标准,用过的人多,不需要额外培训。
       4. Maven的plugin比较多,可以有更多功能,Maven现有体系比较开放,采用的技术相对比较通用和成熟,plugin的机制也可以便于我们扩展更多功能。
       5. Maven的库下载是即用即下,不需要实现全部down下来。Maven的插件也是自动升级,可以方便的我们扩展新功能。
       6. 可以很方便的与eclipse, IDEA这样的主流的IDE集成
       7. 版本管理功能,这里的版本管理不是指第三方库的版本管理,而是项目的版本管理
       8. 站点功能:它的出现让我们可以对项目的状态一目了然,可以自动的把项目的状态和各种报表以站点的形式发布到内部网或者外部网,可以随时随地查看项目状态。有很多中报表可以选择,包括,doc生成,代码规范的检查,自动bug检查,单元测试报表,单元测试的代码覆盖率报表。
      总之,Maven作为一个构建工具,不仅帮我们自动化构建,还能抽象构建过程,提供构建任务实现.他跨平台,对外提供一致的操作接口,这一切足以使他成为优秀的,流行的构建工具.
但是Maven不仅是构建工具,他还是一个依赖管理工具和项目信息管理工具.他还提供了中央仓库,能帮我们自动下载构件.
使用Maven还能享受一个额外的好处,即Maven对于项目目录结构、测试用例命名方式等内容都有既定的规则,只要遵循了这些成熟的规则,用户在项目间切换的时候就免去了额外的学习成本,可以说是约定优于配置(Convention Over Configuration)。

Maven环境搭建
a)Apache Maven下载站点:http://maven.apache.org/download.html
b)maven的安装
把Maven解压到安装目录后,需要设置两个环境变量——PATH和M2_HOME。设置这两个环境变量,假设Maven安装目录是 c:\Program Files\maven-2.0.9,

打开-》计算机-》属性-》高级系统设置-》环镜变量

键入下面的命令:

下载下来之后,解压,找个路径放进去, 把bin的位置设在环境变量里,新建环境变量MAVEN_HOME


在PATH里加入maven的bin的路径


c)验证Maven安装

由于Maven依赖Java运行环境,因此使用Maven之前需要配置Java的运行环境。下载并安装JDK,配置JDK的环境变量JAVA_HOME,否则maven将无法使用

配置完毕后,在Windows命令提示符下,输入mvn -v测试一下,配置成功显示如图:



4.3、MyBatis自动代码生成

具体看我的另一博文http://blog.csdn.net/evankaka/article/details/47023955

4.4、SVN使用

SVN是Subversion的简称,是一个开放源代码的版本控制系统,相较于RCS、CVS,它采用了分支管理系统,它的设计目标就是取代CVS。

集中式管理的工作流程如下图:


      集中式代码管理的核心是服务器,所有开发者在开始新一天的工作之前必须从服务器获取代码,然后开发,最后解决冲突,提交。所有的版本信息都放在服务器上。如果脱离了服务器,开发者基本上可以说是无法工作的。下面举例说明:
开始新一天的工作:
1、从服务器下载项目组最新代码。
2、进入自己的分支,进行工作,每隔一个小时向服务器自己的分支提交一次代码(很多人都有这个习惯。因为有时候自己对代码改来改去,最后又想还原到前一个小时的版本,或者看看前一个小时自己修改了哪些代码,就需要这样做了)。
3、下班时间快到了,把自己的分支合并到服务器主分支上,一天的工作完成,并反映给服务器。
这就是经典的svn工作流程,从流程上看,有不少缺点,但也有优点。

安装

1、IDE中安装SVN插件

Eclipse中安装可以看,http://now51jq.blog.51cto.com/3474143/1571625

VS中可以安装VisualSVN,它的下载地址:https://www.visualsvn.com/。安装过程:http://blog.csdn.net/lincyang/article/details/5658274(VS上还推荐安装小番茄助手,很强大的一个代码提示插件)

2、TortoiseSVN

   这是一个带界面的SVN软件,可以在windows上来使用。有需要可以到http://tortoisesvn.net/来下载。然后直接一路安装即可。

五、其它辅助工具

1、NodePate++

    可以用来打开各种文件,如java,xml、配置文件等等

2、DBVisualizer

    DbVisualizer是一个完全基于JDBC的跨平台数据库管理工具,内置SQL语句编辑器(支持语法高亮),凡是具有JDBC数据库接口的数据库都可以管理,已经在Oracle, Sybase, DB2, Informix, MySQL, InstantDB, Cloudcape, HyperSonic ,Mimer SQL上通过测试

3、Fiddler

Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的“进出”Fiddler的数据(指cookie,html,js,css等文件,这些都可以让你胡乱修改的意思)。 Fiddler 要比其他的网络调试器要更加简单,因为它不仅仅暴露http通讯还提供了一个用户友好的格式。

4、SecureCRT

   SecureCRT是一款支持SSH(SSH1和SSH2)的终端仿真程序,简单地说是Windows下登录UNIX或Linux服务器主机的软件。

5、其它Eclipse插件
编码标准:CheckStyle 插件URL:http://eclipse-cs.sourceforge.net/update/
代码重复:PMD的CPD 插件URL:http://pmd.sourceforge.net/eclipse/
代码覆盖率:Eclemma 插件URL:http://update.eclemma.org
依赖项分析:JDepend 插件URL:http://andrei.gmxhome.de/eclipse/
复杂度分析:Eclipse Metric 插件URL:http://metrics.sourceforge.net/update

document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)
    <div id="digg" articleid="47356915">        <dl id="btnDigg" class="digg digg_enable" onclick="btndigga();">             <dt>顶</dt>            <dd>13</dd>        </dl>        <dl id="btnBury" class="digg digg_enable" onclick="btnburya();">              <dt>踩</dt>            <dd>1</dd>                       </dl>    </div> <div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);">&nbsp;</a>   </div><div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);">&nbsp;</a></div><script type="text/javascript">    function btndigga() {        $(".tracking-ad[data-mod='popu_222'] a").click();    }    function btnburya() {        $(".tracking-ad[data-mod='popu_223'] a").click();    }        </script>


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 动车晚点赶不上下一趟车怎么办 动车晚点导致没赶上下一趟怎么办 浙大三位一体选考分数报错了怎么办 报到证上时间到期了还没报到怎么办 不停的打嗝已经超过24小时怎么办 面对不给下属做主的领导怎么办 法院说退款受伤人去不了证明怎么办 e栈快递柜没收到短信怎么办 京东快递放门卫丢了怎么办 丰巢快递柜收不到取件码怎么办 丰巢快递柜手机号码填错了怎么办 e栈手机号换了取不出来怎么办 买高铁票起点一样终点不一样怎么办 定火车票把名字写错一个字怎么办 火车票坐完车票丢了报销怎么办 客户交给我的钱被骗了怎么办 要证明网络来源的可靠性该怎么办 魅族手机高德地图信号弱怎么办 t恤的印花粘粘的怎么办 从包图网下载的模板素材丢失怎么办 大屏导航的语音功能怎么办用 手机导航不走地图上面走时怎么办 行车撞到步行人死亡师机逃离怎么办 小天才平板电脑不显示了怎么办 高德地图导航不显示车速怎么办 桥梁梁片强度达不到设计要求怎么办 新车交车检验表客户没签字怎么办 中铁快运职工拒绝提货要怎么办 奇瑞a3暖风水箱爆了怎么办 别人挖鱼塘占了我的山土怎么办 自己的鱼塘让别人强行占住了怎么办 公路扩路占地占了鱼塘怎么办? 玉米皮编垫子编好后玉米绳怎么办 入户门门框未预留纱窗位怎么办 门和墙有2cm缝隙怎么办 支座预埋钢板忘记埋了怎么办 做完线雕一边紧一边松怎么办 卖家把没发货的填写了单号怎么办 买的人民币白银亏了好多钱怎么办 带控制线的三相四线开关怎么办 覆膜除尘布袋风拉不动怎么办