JAVA常用工具类

来源:互联网 发布:网站下载器 mac 编辑:程序博客网 时间:2024/06/08 01:28

引言

说起工具类,大家都不会陌生。常用的工具类有Apache 的Commons、 Google 的Guava、以及处理时间日期的Joda扩展包。那么本文主要来讲这几个工具类中的一些方法以及自己写的工具类。

代码

Commons

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.apache.commons.collections.Bag;import org.apache.commons.collections.BidiMap;import org.apache.commons.collections.Factory;import org.apache.commons.collections.HashBag;import org.apache.commons.collections.bidimap.TreeBidiMap;import org.apache.commons.collections.list.LazyList;import org.apache.commons.lang.RandomStringUtils;import org.apache.commons.lang.StringUtils;import org.apache.commons.lang.WordUtils;/** * * Title: langTest* Description: Apache commons工具包测试* Version:1.0.0  * @author pancm */public class test {    public static void main(String[] args) {        stringTest();        otherTest();    }    /**     * StringUtils 相关测试     */    private static void stringTest(){        /*         * 空指针判断         */        String str="";        String str2=null;        String str3=" ";        System.out.println(":"+StringUtils.isEmpty(str));       //:true        System.out.println("null:"+StringUtils.isEmpty(str2));  //null:true        System.out.println(" :"+StringUtils.isEmpty(str3));     // :false        /*         * 判断是否为数字         */        String str4="123";        String str5="12 3";        String str6="123QD#";        System.out.println("str4:"+StringUtils.isNumeric(str4));//str4:true        System.out.println("str5:"+StringUtils.isNumeric(str5));//str5:false        System.out.println("str6:"+StringUtils.isNumeric(str6));//str6:false        /*         * 统计子字符串出现的次数         */        String str7="abcdefgfedccfg";        String str8="ac";        String str9="c";        System.out.println("count:"+StringUtils.countMatches(str7, str8));//count:0        System.out.println("count:"+StringUtils.countMatches(str7, str9));//count:3    }    /**     * 其他的测试     */    private static void otherTest(){        System.out.println("十位数字随机数:"+RandomStringUtils.randomNumeric(10)); //0534110685        System.out.println("十位字母随机数:"+RandomStringUtils.randomAlphabetic(10)); //jLWiHdQhHg        System.out.println("十位ASCII随机数:"+RandomStringUtils.randomAscii(10));  //8&[bxy%h_-        String str="hello world,why are you so happy";        System.out.println("首字符大写:"+WordUtils.capitalize(str));  //:Hello World,why Are You So Happy    }    /**     * Bag 测试     * 主要测试重复元素的统计     */    @SuppressWarnings("deprecation")    private static void bagTest(){        //定义4种球        Bag box=new HashBag(Arrays.asList("red","blue","black","green"));        System.out.println("box.getCount():"+box.getCount("red"));//box.getCount():1        box.add("red", 5);//红色的球增加五个        System.out.println("box.size():"+box.size());   //box.size():9        System.out.println("box.getCount():"+box.getCount("red"));//box.getCount():6    }    /**     * Lazy测试     * 需要该元素的时候,才会生成     */    @SuppressWarnings("unchecked")    private static void lazyTest(){        List<String> lazy=LazyList.decorate(new ArrayList<>(), new Factory() {            @Override            public Object create() {                return "Hello";            }        });         //访问了第三个元素,此时0和1位null        //get几就增加了几加一 , 输出依旧是 Hello         String str=lazy.get(2);        System.out.println("str:"+str);//str:Hello         //加入的第四个元素        lazy.add("world");        //元素总个为4个        System.out.println("lazy.size():"+lazy.size());//lazy.size():4    }    /**     * 双向Map     * 唯一的key和map,可以通过键或值来操作     * 比如删除、查询等     */    private static void bidimapTest(){        BidiMap map=new TreeBidiMap();        map.put(1, "a");        map.put(2, "b");        map.put(3, "c");        System.out.println("map:"+map); //map:{1=a, 2=b, 3=c}        System.out.println("map.get():"+map.get(2)); //map.get():b        System.out.println("map.getKey():"+map.getKey("a")); //map.getKey():1        System.out.println("map.removeValue():"+map.removeValue("c")); //map.removeValue():3        System.out.println("map:"+map); //map:{1=a, 2=b}    }   }

Guava

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.google.common.base.Joiner;import com.google.common.base.Predicate;import com.google.common.base.Splitter;import com.google.common.collect.ArrayListMultimap;import com.google.common.collect.HashBasedTable;import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Maps;import com.google.common.collect.Multimap;import com.google.common.collect.Table;import com.google.common.primitives.Ints;/** * * Title: guavaTest* Description:谷歌 guava 工具包测试* Version:1.0.0  * @author pancm */public class guavaTest {    public static void main(String[] args) {        noChangeList();        one2MoreMap();        more2One();        filtedMap();        joiner();        splitter();        integer();    }    /**     * 不可变集合测试     */    private static void noChangeList(){        ImmutableList<String> list=ImmutableList.of("A","B","C");        ImmutableMap<Integer,String> map=ImmutableMap.of(1,"壹",2,"贰",3,"叁");        System.out.println("ImmutableList:"+list); //ImmutableList:[A, B, C]        System.out.println("ImmutableMap:"+map); //ImmutableMap:{1=壹, 2=贰, 3=叁}        //下面运行直接报错,因为这是不可变集合//      list.add("D");  //      map.put(4, "肆");    }    /**     * map中多个键的测试     * 例如:一个人多个电话     */    private static void one2MoreMap(){        Multimap<String,String> map= ArrayListMultimap.create();        map.put("路人甲", "123");        map.put("路人甲", "234");        map.put("路人乙", "567");        map.put("路人乙", "890");        System.out.println("Multimap:"+map); //Multimap:{路人乙=[567, 890], 路人甲=[123, 234]}        System.out.println("get:"+map.get("路人乙")); //get:[567, 890]    }    /**     * 多个键值对一个值     * 例如:坐标     */    private static void more2One(){        Table<Double, Double, String> table=HashBasedTable.create();        table.put(22.54, 114.01, "深圳");        table.put(39.96, 116.40, "北京");        System.out.println("Table:"+table); //Table:{22.54={114.01=深圳}, 39.96={116.4=北京}}        System.out.println("Table.get:"+table.get(22.54, 114.01));//Table.get:深圳    }    /**     * Map的过滤     * 例如:查找该集合中大于20岁的人     */    private static void filtedMap(){        Map<String,Integer> map=new HashMap<String,Integer>();        map.put("张三", 19);        map.put("李四", 20);        map.put("王五", 21);        Map<String,Integer> filtedmap =Maps.filterValues(map,                 new Predicate<Integer>(){                    @Override                    public boolean apply(Integer age) {                        return age>20;                    }        });        System.out.println("Map:"+map); //Map:{张三=19, 李四=20, 王五=21}        System.out.println("filtedmap:"+filtedmap);//filtedmap:{王五=21}    }    /**     * Joiner连接测试     * 不局限于连接String,如果是null,会直接跳过     *      */    private static void joiner(){        //设置连接符         //如:设置为 "和",拼接 “你”,“我” 就变成了“你和我”        Joiner joiner=Joiner.on(",");        String str=joiner.skipNulls().join("你好","java");        Map<String,String> map=new HashMap<String,String>();        map.put("张三", "你好");        map.put("李四", "嗨");        //设置键值的连接符以及键与值之间的连接符        String str1=Joiner.on(",").withKeyValueSeparator(":").join(map);        System.out.println("Joiner: "+str); //Joiner: 你好,java        System.out.println("Joiner: "+str1); //Joiner: 张三:你好,李四:嗨    }    /**     * Splitter拆分测试     */    private static void splitter(){        String str="你好,java";        //按字符分割        for(String s:Splitter.on(",").split(str)){            System.out.println("s:"+s);        }        //按固定长度分割        for(String d:Splitter.fixedLength(2).split(str)){            System.out.println("d:"+d);        }    }    /**     * 基本类型测试     */    private static void integer(){        int []ints={1,4,3,2};        //找到里面的最大值        System.out.println("max:"+Ints.max(ints)); //max:4        List<Integer> list=new ArrayList<Integer>();        list.add(1);        list.add(3);        list.add(6);        //包装类型集合转变为基本类型集合        int []arr=Ints.toArray(list);        for(int i=0,j=arr.length;i<j;i++){            System.out.println("arr:"+arr[i]);        }    }}

Joda

import java.util.Date;import java.util.Locale;import org.joda.time.DateTime;import org.joda.time.DateTimeZone;import org.joda.time.Hours;import org.joda.time.MutableDateTime;import org.joda.time.format.DateTimeFormat;/** * * Title: jodaTest* Description: Joda 时间工具包测试* Version:1.0.0  * @author pancm */public class jodaTest {    public static void main(String[] args) {        jodaTest();    }    /**     * 日期方法     */    private static void jodaTest(){        //当前时间戳        DateTime datetime =new DateTime();        //当前的英文星期几        System.out.println("Week:"+datetime.dayOfWeek().getAsText(Locale.ENGLISH));  //Week:Wednesday        //本地的日期格式        System.out.println("LocalDate:"+datetime.toLocalDate()); //LocalDate:2017-11-02        //本地的当前时间 包含毫秒        System.out.println("LocalDateTime:"+datetime.toLocalDateTime()); //LocalDateTime:2017-11-02T08:40:04.529        //格式化日期        System.out.println("时间:"+datetime.toString(DateTimeFormat.forPattern("yyyy年M月d日")));//时间:2017年11月2日        //加上100小时之后是星期几(中文)        System.out.println("dayOfWeek:"+datetime.plusHours(100).dayOfWeek().getAsText(Locale.CHINA));//dayOfWeek:星期一        //加100天的日期        System.out.println("toLocalDate():"+datetime.plusDays(100).toLocalDate()); //toLocalDate():2018-02-10        //十年前的今天是星期几(默认中文)        System.out.println("minusYears():"+datetime.minusYears(10).dayOfWeek().getAsText()); //minusYears():星期五        //离双11还有多少小时        System.out.println("离双11的时间:"+Hours.hoursBetween(datetime,new DateTime("2017-11-11")).getHours()); //离双11的时间:207        //伦敦的时间:2017-11-02T01:24:15.139Z        System.out.println("伦敦的时间:"+datetime.withZone(DateTimeZone.forID("Europe/London")));//伦敦的时间:2017-11-02T01:24:15.139Z        //标准时间        System.out.println("标准时间:"+datetime.withZone(DateTimeZone.UTC));        //当前可变的时间        MutableDateTime mdt=new MutableDateTime();        //10年后的时间        DateTime dt=datetime.plusYears(10);        System.out.println("十年之后:"+dt); //2027-11-02T09:06:36.883+08:00        while(mdt.isBefore(dt)){            //循环一次加一天            mdt.addDays(1);            //是13号,并且是星期五            if(mdt.getDayOfMonth()==13&&mdt.getDayOfWeek()==5){                //打印出十年内所有的黑色星期五                System.out.println("星期五:"+mdt);                /*                 *  星期五:2018-04-13T09:13:40.551+08:00                    星期五:2018-07-13T09:13:40.551+08:00                    星期五:2019-09-13T09:13:40.551+08:00                    星期五:2019-12-13T09:13:40.551+08:00                    星期五:2020-03-13T09:13:40.551+08:00                    星期五:2020-11-13T09:13:40.551+08:00                    星期五:2021-08-13T09:13:40.551+08:00                    星期五:2022-05-13T09:13:40.551+08:00                    星期五:2023-01-13T09:13:40.551+08:00                    星期五:2023-10-13T09:13:40.551+08:00                    星期五:2024-09-13T09:13:40.551+08:00                    星期五:2024-12-13T09:13:40.551+08:00                    星期五:2025-06-13T09:13:40.551+08:00                    星期五:2026-02-13T09:13:40.551+08:00                    星期五:2026-03-13T09:13:40.551+08:00                    星期五:2026-11-13T09:13:40.551+08:00                    星期五:2027-08-13T09:13:40.551+08:00                 */            }        }        //转换成jdk的Date格式        Date jdkDate=datetime.toDate();        System.out.println("jdkDate:"+jdkDate);  //jdkDate:Thu Nov 02 09:51:13 CST 2017        //jdk的Date转换成Joda的Date        datetime=new DateTime(jdkDate);        System.out.println("JodaDate:"+datetime);//JodaDate:2017-11-02T09:51:13.691+08:00    }}

MyTools

自己写的工具类以及一些测试示例

import java.io.IOException;import java.io.UnsupportedEncodingException;import java.math.BigInteger;import java.net.InetAddress;import java.net.UnknownHostException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Timestamp;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.Enumeration;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Random;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.test.pojoTest.User;/** *  * Title: MyTools  * Description:常用工具类 * Version:1.0.1 * 增加JSON相关转换 ,增加HttpServletRequest转换JSON格式 * @author pancm */public final class MyTools {    /** 时间格式包含毫秒 */    private static final String sdfm = "yyyy-MM-dd HH:mm:ss SSS";    /** 普通的时间格式 */    private static final String sdf = "yyyy-MM-dd HH:mm:ss";    /** 时间戳格式 */    private static final String sd = "yyyyMMddHHmmss";    /** 检查是否为整型 */    private static  Pattern p=Pattern.compile("^\\d+$");    /**     * 判断String类型的数据是否为空      * null,""," " 为true      * "A"为false     *      * @return boolean     */    public static boolean isEmpty(String str) {        return (null == str || str.trim().length() == 0);    }    /**     * 判断String类型的数据是否为空      * null,"", " " 为false      * "A", 为true     *      * @return boolean     */    public static boolean isNotEmpty(String str) {        return !isEmpty(str);    }    /**     * 判断list类型的数据是否为空      * null,[] 为 true     *      * @return boolean     */    @SuppressWarnings("rawtypes")    public static boolean isEmpty(List list) {        return (null == list || list.size() == 0);    }    /**     * 判断list类型的数据是否为空      * null,[] 为 false     *      * @return boolean     */    @SuppressWarnings("rawtypes")    public static boolean isNotEmpty(List list) {        return !isEmpty(list);    }    /**     * 判断Map类型的数据是否为空      * null,[] 为true      *      * @return boolean     */    @SuppressWarnings("rawtypes")    public static boolean isEmpty(Map map) {        return (null == map || map.size()==0);    }    /**     * 判断map类型的数据是否为空      * null,[] 为 false     *      * @return boolean     */    @SuppressWarnings("rawtypes")    public static boolean isNotEmpty(Map map) {        return !isEmpty(map);    }    /**     * 判断JSONObject类型的数据是否为空      * null,[] 为true      *      * @return boolean     */    public static boolean isEmpty(JSONObject json) {        return (null == json || json.size()==0);    }    /**     * 判断json类型的数据是否为空      * null,[] 为 false     *      * @return boolean     */    public static boolean isNotEmpty(JSONObject json) {        return !isEmpty(json);    }    /**     * 字符串反转     * 如:入参为adc,出参则为cba     * @param str      * @return       */    public static String reverse(String str) {        if(isEmpty(str)){             return str;        }        return reverse(str.substring(1)) + str.charAt(0);    }    /**     * 获取当前long类型的的时间     *      * @return long     */    public static long getNowLongTime() {        return System.currentTimeMillis();    }    /**     * long类型的时间转换成 yyyyMMddHHmmss String类型的时间     *      * @param lo long类型的时间     * @return     */    public static String longTime2StringTime(long lo) {        return longTime2StringTime(lo, sd);    }    /**     * long类型的时间转换成自定义时间格式     *      * @param lo     long类型的时间     * @param format  时间格式     * @return String     */    public static String longTime2StringTime(long lo, String format) {        return new SimpleDateFormat(format).format(lo);    }    /**     * 获取当前String类型的的时间 使用默认格式 yyyy-MM-dd HH:mm:ss     *      * @return String     */    public static String getNowTime() {        return getNowTime(sdf);    }    /**     * 获取当前String类型的的时间(自定义格式)     * @param format  时间格式     * @return String     */    public static String getNowTime(String format) {        return new SimpleDateFormat(format).format(new Date());    }    /**     * 获取当前Timestamp类型的的时间     *      * @return Timestamp     */    public static Timestamp getTNowTime() {        return new Timestamp(getNowLongTime());    }    /**     * 获取的String类型的当前时间并更改时间     * @param number  要更改的的数值     * @param format  更改时间的格式  如yyyy-MM-dd HH:mm:ss     * @param type   更改时间的类型    时:h; 分:m ;秒:s     * @return  String     */    public static String changeTime(int number,String format,String type) {        return changeTime(number,format,type,"");    }    /**     * 获取的String类型时间并更改时间     * @param number 要更改的的数值     * @param format 更改时间的格式     * @param type   更改时间的类型 。时:h; 分:m ;秒:s      * @param time    更改的时间       没有则取当前时间     * @return String     */    public static String changeTime(int number,String format,String type,String time) {        if(isEmpty(time)){ //如果没有设置时间则取当前时间            time=getNowTime(format);        }        SimpleDateFormat format1 = new SimpleDateFormat(format);        Date d=null;        try {            d = format1.parse(time);        } catch (Exception e) {            e.printStackTrace();        }            Calendar ca = Calendar.getInstance();  //定义一个Calendar 对象        ca.setTime(d);//设置时间        if("h".equals(type)){            ca.add(Calendar.HOUR, number);//改变时        }else if("m".equals(type)){            ca.add(Calendar.MINUTE, number);//改变分        }else if("s".equals(type)){            ca.add(Calendar.SECOND, number);//改变秒        }        String backTime = format1.format(ca.getTime());  //转化为String 的格式        return backTime;    }    /**     * 两个日期带时间比较     * 第二个时间大于第一个则为true,否则为false     * @param String      * @return boolean     * @throws ParseException      */    public static boolean compareDay(String time1,String time2,String format) {          if(isEmpty(format)){//如果没有设置格式使用默认格式                format=sdf;            }            SimpleDateFormat s1 = new SimpleDateFormat(format);            Date t1=null;            Date t2 =null;            try {                t1 = s1.parse(time1);                t2=s1.parse(time2);            } catch (ParseException e) {                e.printStackTrace();            }            return t2.after(t1);//当 t2 大于 t1 时,为 true,否则为 false        }    /**     * 判断是否为整型     * @param String                * @return boolean      */       public static boolean isInteger(String str) {        Matcher m = p.matcher(str);        return m.find();    }    /**     * 自定义位数产生随机数字     * @param int     * @return String     */    public static String random(int count) {        char start = '0';        char end = '9';        Random rnd = new Random();        char[] result = new char[count];        int len = end - start + 1;        while (count-- > 0) {            result[count] = (char) (rnd.nextInt(len) + start);        }        return new String(result);    }    /**       * 获取自定义长度的随机数(含字母)    * @param len  长度    * @return String    */    public static String random2(int len){         int random= Integer.parseInt(random(5));        Random rd = new Random(random);          final int  maxNum = 62;          StringBuffer sb = new StringBuffer();          int rdGet;//取得随机数          char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',                  'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',                  'x', 'y', 'z', 'A','B','C','D','E','F','G','H','I','J','K',                  'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',                  'X', 'Y' ,'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };          int count=0;          while(count < len){              rdGet = Math.abs(rd.nextInt(maxNum));//生成的数最大为62-1              if (rdGet >= 0 && rdGet < str.length) {                  sb.append(str[rdGet]);                  count ++;              }          }          return sb.toString();      }    /**     * 获取本机ip     *      * @return String     * @throws UnknownHostException     */    public static String getLocalHostIp() throws UnknownHostException {        return InetAddress.getLocalHost().getHostAddress();    }    /**     * 获取客户端ip     * @return String     * @throws UnsupportedEncodingException      */    public static String getClientIp(HttpServletRequest request) throws  UnsupportedEncodingException {        request.setCharacterEncoding("utf-8");        return request.getRemoteAddr();    }    /**     * 获取客户端port     * @return int     * @throws UnsupportedEncodingException      */    public static int getClientPort(HttpServletRequest request) throws  UnsupportedEncodingException {        request.setCharacterEncoding("utf-8");        return request.getRemotePort();    }     /**      * 获取request请求参数并以JSON形式返回      * @param  HttpServletRequest      * @return JSONObject      * @throws IOException      */     @SuppressWarnings("rawtypes")     public static JSONObject  getParameterNames(HttpServletRequest request) throws IOException{         JSONObject json=new JSONObject();         Enumeration enu=request.getParameterNames();          String key="",value="";         while(enu.hasMoreElements()){               key=(String)enu.nextElement();              value= request.getParameter(key);             json.put(key,value);         }        return json;       }    /**     *  JSON 转换为 JavaBean     * @param json     * @param t     * @return <T>     */    public static <T> T toBean(JSONObject json,Class<T> t){         return JSON.toJavaObject(json,t);      }    /**     *  JSON 字符串转换为 JavaBean     * @param str     * @param t     * @return <T>     */    public static <T> T toBean(String str,Class<T> t){         return JSON.parseObject(str,  t);      }    /**     * JSON 字符串 转换成JSON格式      * @param obj     * @return JSONObject     */    public static JSONObject toJson(String str){        if(isEmpty(str)){            return new JSONObject();        }        return JSON.parseObject(str);    }    /**     *  JavaBean 转化为JSON     * @param t     * @return     */    public static  JSONObject toJson(Object t){        if(null==t||"".equals(t)){            return new JSONObject();        }        return (JSONObject) JSON.toJSON(t);    }    /**     * JSON 字符串转换为 HashMap     *      * @param json     *            - String     * @return Map     */    @SuppressWarnings("rawtypes")    public static Map toMap(String json) {        if (isEmpty(json)) {            return new HashMap();        }        return JSON.parseObject(json, HashMap.class);    }    /**       * 将map转化为string       * @param m       * @return       */      @SuppressWarnings("rawtypes")    public static String toString(Map m) {          return JSONObject.toJSONString(m);      }        /**       *  String转换为数组        * @param text       * @return       */    public static <T> Object[] toArray(String text) {          return toArray(text, null);      }      /**     *  String转换为数组      * @param text     * @return     */    public static <T> Object[] toArray(String text, Class<T> clazz) {          return JSON.parseArray(text, clazz).toArray();      }      /**     * name1=value1&name2=value2格式的数据转换成json数据格式     * @param str     * @return     */    public static JSONObject str2Json(String str){        if(isEmpty(str)){            return new JSONObject();        }        JSONObject json=new JSONObject();        String [] str1=str.split("&");        String str3="",str4="";        if(null==str1||str1.length==0){            return new JSONObject();        }        for(String str2:str1){            str3=str2.substring(0, str2.lastIndexOf("="));            str4=str2.substring(str2.lastIndexOf("=")+1, str2.length());            json.put(str3, str4);        }        return json;    }    /**     * json数据格式 转换成name1=value1&name2=value2格式     * @param str     * @return     */    @SuppressWarnings("rawtypes")    public static String json2Str(JSONObject json){         if(isEmpty(json)){            return null;         }          StringBuffer sb=new StringBuffer();          Iterator it=json.entrySet().iterator(); //定义迭代器          while(it.hasNext()){             Map.Entry  er= (Entry) it.next();             sb.append(er.getKey());             sb.append("=");             sb.append(er.getValue());             sb.append("&");          }          sb.delete(sb.length()-1, sb.length()); //去掉最后的&        return sb.toString();    }    /**     * 将JDBC查询的数据转换成List类型     * @param ResultSet     * @return List     * @throws SQLException     */    @SuppressWarnings({ "rawtypes", "unchecked" })    public static List convertList(ResultSet rs) throws SQLException {        if(null==rs){            return new ArrayList<>();        }        List list = new ArrayList();        ResultSetMetaData md = rs.getMetaData();        int columnCount = md.getColumnCount();        while (rs.next()) {            JSONObject rowData = new JSONObject();            for (int i = 1; i <= columnCount; i++) {                rowData.put(md.getColumnName(i), rs.getObject(i));            }            list.add(rowData);        }        return list;    }  /**     * MD5加密     * @param message     * @return     */    public static String encode(String message) {        byte[] secretBytes = null;        try {            secretBytes = MessageDigest.getInstance("md5").digest(                    message.getBytes());        } catch (NoSuchAlgorithmException e) {            throw new RuntimeException("没有md5这个算法!");        }        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字        // 如果生成数字未满32位,需要前面补0        int length=32 - md5code.length();        for (int i = 0; i <length ; i++) {            md5code = "0" + md5code;        }        return md5code;    }    /**     * 本方法的测试示例     * @param args     */    @SuppressWarnings({ "rawtypes", "unchecked" })    public static void main(String[] args) {        /*         * String 和List 空数据判断         */        String str1="";        String str2=" ";        String str3=null;        String str4="a";        List list=null;        List list2=new ArrayList();        List list3=new ArrayList();        list3.add("a");        System.out.println("str1 :"+isEmpty(str1));     //str1 :true        System.out.println("str2 :"+isEmpty(str2));     //str2 :true        System.out.println("str3 :"+isEmpty(str3));     //str3 :true        System.out.println("str4 :"+isEmpty(str4));     //str4 :false        System.out.println("list :"+isEmpty(list));     //list :true        System.out.println("list2 :"+isEmpty(list2));   //list2 :true        System.out.println("list3 :"+isEmpty(list3)); //list3 :false        /*         *  时间         */        long start=getNowLongTime();        System.out.println("getNowTime():"+getNowTime());       //getNowTime():2017-09-26 17:46:44        System.out.println("getNowLongTime():"+getNowLongTime());  //getNowLongTime():1506419204920        System.out.println("getNowTime(sdfm):"+getNowTime(sdfm)); //getNowTime(sdfm):2017-09-26 17:46:44 920        System.out.println("当时时间向前推移30秒:"+ changeTime(-30,sdf,"s"));            //2017-09-26 17:46:14         System.out.println("时间比较:"+compareDay(getNowTime(sdfm),changeTime(-30,sdf,"s"),"")); //时间比较:false        System.out.println("getTNowTime():"+getTNowTime()); //getTNowTime():2017-09-26 17:46:44.921        System.out.println("LongTime2StringTime():"+longTime2StringTime(start, sd)); //LongTime2StringTime():20170926174644        /*         * 整型判断         */        String st="258369";        String st2="258369A!@";        String st3="258  369 ";        System.out.println("st:"+isInteger(st));  //st:true        System.out.println("st2:"+isInteger(st2)); //st2:false        System.out.println("st3:"+isInteger(st3)); //st3:false        /*         * 字符串反转         */        String re="abcdefg";        System.out.println("字符串反转:"+reverse(re)); //字符串反转:gfedcba        /*         * 本机IP         */        try {            System.out.println("本机IP:"+getLocalHostIp()); //本机IP:192.168.1.111        } catch (UnknownHostException e) {            e.printStackTrace();        }        /*         * 随机数         */        System.out.println("6位随机数:"+random(6)); //6位随机数:222488        System.out.println("10位随机数:"+random2(10));  //10位随机数:ZwW0pmofjW        /*         * JSON数据转换         */        String value="name1=value1&name2=value2&name3=value3";        JSONObject json=new JSONObject();        json.put("name1", "value1");        json.put("name2", "value2");        json.put("name3", "value3");        System.out.println("value:"+value);               //value:name1=value1&name2=value2&name3=value3        System.out.println("str2Json:"+str2Json(value));  //str2Json:{"name1":"value1","name2":"value2","name3":"value3"}        System.out.println("json:"+json.toJSONString());  //json:{"name1":"value1","name2":"value2","name3":"value3"}        System.out.println("json2Str:"+json2Str(json));  //json2Str:name3=value3&name1=value1&name2=value2        String jsonString=json.toJSONString();        System.out.println("jsonString:"+jsonString);       //{"name1":"value1","name2":"value2","name3":"value3"}        System.out.println("toJson(jsonString):"+toJson(jsonString)); //toJson(jsonString):{"name1":"value1","name2":"value2","name3":"value3"}        User user=new User();        JSONObject json2=new JSONObject();         user.setId(1);        user.setName("张三");        json2.put("id", 3);        json2.put("name", "王五");        System.out.println("user:"+user);        System.out.println("toBean:"+toBean(json2, User.class));        System.out.println("toJSON:"+toJson(user));    }}

结语

代码:https://github.com/xuwujing/TestMain/blob/master/TestMain/src/com/util/MyTools.java
工具类的一些方法和测试就是这些了,详细的说明已经在代码的注释中了。如果觉得这些方法使用有不妥之处,欢迎指出!

原创粉丝点击