java开发常用工具类总结

本文总结了一些Java开发过程中常用的一些工具类,可以在开发中大大降低开发难度。

目录

1、ConfigurationManager

   属性文件工具类,加载配置文件,可以直接读取配置文件的值。

2、JDBCHelper

   JDBC辅助工具

3、CastUtil

    数据转型工具类

4、DateUtil

   时间如期工具类

5、FileUtil

   文件读写创建工具类

1、ConfigurationManager

属性文件工具类,加载配置文件,可以直接读取配置文件的值。

ConfigurationManager.getProperty(String key)
    输入所要查询的property的key值,返回所要查询的property的value值。
ConfigurationManager.getProperty(String key,String defaultValue) 
    输入所要查询的property的key值,返回所要查询的property的value值。当文件中无此key对应的则返回defaultValue
ConfigurationManager.getString(String key)
    输入所要查询的String的key值,返回所要查询的String的value值。
ConfigurationManager.getString(String key,String defaultValue) 
    输入所要查询的String的key值,返回所要查询的String的value值。当文件中无此key对应的则返回defaultValue

还有getInteger、getBoolean、getLong等与上面类似的使用。

package com.aura.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Read Configuration Information
 * 属性文件工具类
 */
public class ConfigurationManager {

    // create Properties
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class);
    private static Properties prop = new Properties();
    //fileName一定要在class下面及java根目录或者resource跟目录下
    private static final String fileName = "usertrack.properties";

    // static code block ,load configuration properties file
    static {
        InputStream in = null;
        try {
            // create InputStream
            in = ConfigurationManager.class
                    .getClassLoader().getResourceAsStream(fileName);
            // load properties
            prop.load(in);
            if(in==null){
                throw new FileNotFoundException(fileName+"file is not Found");
            }
        }catch (Exception e) {
            LOGGER.error("load properties file filure",e);
        }finally {
            if(in !=null){
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error("close input stream failure",e);
                }
            }
        }
    }

    /**
     * get value By key
     * @param key 所要查询的property的key值
     * @return 所要查询的property的value值
     */
    public static String getProperty(String key) {
            return  prop.getProperty(key);
    }

    /**
     * get value By key
     * @param key 所要查询的property的key值
     * @param defaultValue 当文件中无此key对应的则返回defaultValue
     * @return 所要查询的property的value值
     */
    public static String getProperty(String key,String defaultValue) {
        //return  prop.getProperty(key,defaultValue);
        String value = defaultValue;
        if (prop.containsKey(key)){
            value = getProperty(key);
        }
        return value;
    }

    /**
     * get value By key
     * @param key 所要查询的String的key值
     * @return 所要查询的String的value值
     */
    public static String getString(String key) {
        return  getProperty(key);
    }

    /**
     * get value By key
     * @param key 所要查询的String的key值
     * @param defaultValue 当文件中无此key对应的则返回defaultValue
     * @return 所要查询的String的value值
     */
    public static String getString(String key,String defaultValue) {
        return getProperty(key,defaultValue);
    }


    /**
     * get Integer value By key
     * @param key 所要查询的property的key值
     * @return 所要查询的property的value值的Integer类型
     */
    public static Integer getInteger(String key) {
        String value = getProperty(key);
        try {
            return Integer.valueOf(value);
        } catch (Exception e) {
            LOGGER.error("value is: '"+value +"' Not a numeric string and can not be converted to a number",e);
        }
        return 0;
    }

    /**
     * get value By key
     * @param key 所要查询的property的key值
     * @param defaultValue 当文件中无此key,则返回defaultValue
     * @return 所要查询的property的value值
     */
    public static Integer getInteger(String key,int defaultValue) {
        int value = defaultValue;
        if (prop.containsKey(key)){
            value = getInteger(key);
        }
        return value;
    }

    /**
     * get Boolean value By key
     * @param key 所要查询的property的key值
     * @return 所要查询的property的value值的Boolean类型
     */
    public static Boolean getBoolean(String key) {
        String value = getProperty(key);
        try {
            return Boolean.valueOf(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * get value By key
     * @param key 所要查询的property的key值
     * @param defaultValue 当文件中无此key对应的则返回defaultValue
     * @return 所要查询的property的value值
     */
    public static Boolean getBoolean(String key,Boolean defaultValue) {
        Boolean value = defaultValue;
        if (prop.containsKey(key)){
            String str = getProperty(key);
            if(str.equalsIgnoreCase("true") && str.equalsIgnoreCase("false")){
                value = getBoolean(key);
            }
        }
        return value;
    }

    /**
     * get Loog value By key
     * @param key 所要查询的property的key值
     * @return 所要查询的property的value值的Long类型
     */
    public static Long getLong(String key) {
        String value = getProperty(key);
        try {
            return Long.valueOf(value);
        } catch (Exception e) {
            LOGGER.error("value is: '"+value +"' Not a Long type and can not be converted to a Long",e);
        }
        return 0L;
    }

    /**
     * get value By key
     * @param key 所要查询的property的key值
     * @param defaultValue 当文件中无此key,则返回defaultValue
     * @return 所要查询的property的value值
     */
    public static Long getLong(String key,Long defaultValue) {
        Long value = defaultValue;
        if (prop.containsKey(key)){
            value = getLong(key);
        }
        return value;
    }
}

2、JDBCHelper

JDBC 辅助组件
package com.aura.jdbc;

import com.aura.conf.ConfigurationManager;
import com.aura.constant.Constants;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;

/**
 * JDBC 辅助组件
 *
 * 在正式的项目的代码编写过程中,是完全严格按照大公司的coding标准来的
 * 也就是说,在代码中,是不能出现任何hard code(硬编码)的字符
 * 比如“张三”、“com.mysql.jdbc.Driver”
 * 所有这些东西,都需要通过常量来封装和使用
 *
 */
public class JDBCHelper {

    /**
     * 第一步:在静态代码块中,直接加载数据库的驱动
     */
    static {
        try {
            String driver = ConfigurationManager.getProperty(Constants.JDBC_DRIVER);
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 第二步,实现JDBCHelper的单例化
     */
    private static JDBCHelper instance = null;

    /**
     * 获取单例
     * @return 单例
     */
    public static JDBCHelper getInstance() {
        if(instance == null) {
            synchronized(JDBCHelper.class) {
                if(instance == null) {
                    instance = new JDBCHelper();
                }
            }
        }
        return instance;
    }

    // 数据库连接池
    private LinkedList<Connection> datasource = new LinkedList<Connection>();

    /**
     * 第三步:实现单例的过程中,创建唯一的数据库连接池
     */
    private JDBCHelper() {
        // 首先第一步,获取数据库连接池的大小,就是说,数据库连接池中要放多少个数据库连接
        // 这个,可以通过在配置文件中配置的方式,来灵活的设定
        int datasourceSize = ConfigurationManager.getInteger(
                Constants.JDBC_DATASOURCE_SIZE);

        // 然后创建指定数量的数据库连接,并放入数据库连接池中
        for(int i = 0; i < datasourceSize; i++) {
            String url = ConfigurationManager.getProperty(Constants.JDBC_URL);
            String user = ConfigurationManager.getProperty(Constants.JDBC_USER);
            String password = ConfigurationManager.getProperty(Constants.JDBC_PASSWORD);
            try {
                Connection conn = DriverManager.getConnection(url, user, password);
                datasource.push(conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 第四步,提供获取数据库连接的方法
     */
    public synchronized Connection getConnection() {
        while(datasource.size() == 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return datasource.poll();
    }

    /**
     *
     * 第五步:开发增删改查的方法
     * 1、执行增删改SQL语句的方法
     * 2、执行查询SQL语句的方法
     * 3、批量执行SQL语句的方法
     */
    /**
     * 执行增删改SQL语句
     * @param sql
     * @param params
     * @return 影响的行数
     */
    public int executeUpdate(String sql, Object[] params) {
        int rtn = 0;
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for(int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            rtn = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                datasource.push(conn);
            }
        }

        return rtn;
    }

    /**
     * 执行查询SQL语句
     * @param sql
     * @param params
     * @param callback
     */
    public void executeQuery(String sql, Object[] params,
                             QueryCallback callback) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for(int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            rs = pstmt.executeQuery();

            callback.process(rs);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                datasource.push(conn);
            }
        }
    }

    /**
     * 静态内部类:查询回调接口
     * @author Administrator
     *
     */
    public static interface QueryCallback {

        /**
         * 处理查询结果
         * @param rs
         * @throws Exception
         */
        void process(ResultSet rs) throws Exception;

    }
}

3、CastUtil

 数据转型工具类

package com.aura.utils;

import jodd.util.StringUtil;

/**
 * CastUtil
 * @description: 数据转型工具类
 **/
public class CastUtil {
    /**
     * @Description: 转为String类型
     * @Param: [obj]
     * @return: java.lang.String 如果参数为null则转为空字符串
     */
    public static String castString(Object obj){
        return CastUtil.castString(obj,"");
    }

    /**
     * @Description: 转为String类型(提供默认值)
     * @Param: [obj, defaultValue] 将obj转为string,如果obj为null则返回default
     * @return: String
     */
    public static String castString(Object obj,String defaultValue){
        return obj!=null?String.valueOf(obj):defaultValue;
    }

    /**
     * @Description: 转为double类型,如果为null或者空字符串或者格式不对则返回0
     * @Param: [obj]
     * @return: String
     */
    public static double castDouble(Object obj){
        return CastUtil.castDouble(obj,0);
    }

    /**
     * @Description: 转为double类型 ,如果obj为null或者空字符串或者格式不对则返回defaultValue
     * @Param: [obj, defaultValue]
     * @return: String obj为null或者空字符串或者格式不对返回defaultValue
     */
    public static double castDouble(Object obj,double defaultValue){
        double value = defaultValue;  //声明结果,把默认值赋给结果
        if (obj!=null){   //判断是否为null
            String strValue = castString(obj);  //转换为String
            if (StringUtil.isNotEmpty(strValue)){   //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
                try{
                    value = Double.parseDouble(strValue);  //不为空则把值赋给value
                }catch (NumberFormatException e){
                    value = defaultValue;  //格式不对把默认值赋给value
                }
            }
        }
        return value;
    }

    /**
     * 转为long型,如果obj为null或者空字符串或者格式不对则返回0
     * @param obj
     * @return
     */
    public static long castLong(Object obj){
        return CastUtil.castLong(obj,0);
    }

    /**
     * 转为long型(提供默认数值),如果obj为null或者空字符串或者格式不对则返回defaultValue
     * @param obj
     * @param defaultValue
     * @return obj为null或者空字符串或者格式不对返回defaultValue
     */
    public static long castLong(Object obj,long defaultValue){
        long value = defaultValue;  //声明结果,把默认值赋给结果
        if (obj!=null){   //判断是否为null
            String strValue = castString(obj);  //转换为String
            if (StringUtil.isNotEmpty(strValue)){   //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
                try{
                    value = Long.parseLong(strValue);  //不为空则把值赋给value
                }catch (NumberFormatException e){
                    value = defaultValue;  //格式不对把默认值赋给value
                }

            }
        }
        return value;
    }

    /**
     * 转为int型
     * @param obj
     * @return 如果obj为null或者空字符串或者格式不对则返回0
     */
    public static int castInt(Object obj){
        return CastUtil.castInt(obj,0);
    }

    /**
     * 转为int型(提供默认值)
     * @param obj
     * @param defaultValue
     * @return 如果obj为null或者空字符串或者格式不对则返回defaultValue
     */
    public static int castInt(Object obj,int defaultValue){
        int value = defaultValue;  //声明结果,把默认值赋给结果
        if (obj!=null){   //判断是否为null
            String strValue = castString(obj);  //转换为String
            if (StringUtil.isNotEmpty(strValue)){   //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
                try{
                    value = Integer.parseInt(strValue);  //不为空则把值赋给value
                }catch (NumberFormatException e){
                    value = defaultValue;  //格式不对把默认值赋给value
                }

            }
        }
        return value;
    }

    /**
     * 转为boolean型,不是true的返回为false
     * @param obj
     * @return
     */
    public static boolean castBoolean(Object obj){
        return CastUtil.castBoolean(obj,false);
    }


    /**
     * 转为boolean型(提供默认值)
     * @param obj
     * @param defaultValue
     * @return
     */
    public static boolean castBoolean(Object obj,boolean defaultValue){
        boolean value = defaultValue;
        if (obj!=null){  //为null则返回默认值
            value = Boolean.parseBoolean(castString(obj));  //底层会把字符串和true对比,所以不用判断是否为空字符串
        }
        return value;
    }
}

4、DateUtil

package com.aura.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class DateUtil{


    public static final String DATE_FORMAT_YYYY = "yyyy";

    public static final String DATE_FORMAT_YYYYMM = "yyyyMM";

    public static final String DATE_FORMAT_YYYY_MM = "yyyy-MM";

    public static final String DATE_FORMAT_YYMMDD = "yyMMdd";

    public static final String DATE_FORMAT_YY_MM_DD = "yy-MM-dd";

    public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";

    public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";

    public static final String DATE_FORMAT_POINTYYYYMMDD = "yyyy.MM.dd";

    public static final String DATE_TIME_FORMAT_YYYY年MM月DD日 = "yyyy年MM月dd日";

    public static final String DATE_FORMAT_YYYYMMDDHHmm = "yyyyMMddHHmm";

    public static final String DATE_TIME_FORMAT_YYYYMMDD_HH_MI = "yyyyMMdd HH:mm";

    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI = "yyyy-MM-dd HH:mm";

    public static final String DATE_TIME_FORMAT_YYYYMMDDHHMISS = "yyyyMMddHHmmss";

    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS = "yyyyMMddHHmmssSSS";

    public static final String DATE_FORMAT_MMDDHHMI = "MM-dd HH:mm";


    /* ************工具方法***************   */

    /**
     * 获取某日期的年份
     * @param date
     * @return
     */
    public static Integer getYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取某日期的月份
     * @param date
     * @return
     */
    public static Integer getMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取某日期的日数
     * @param date
     * @return
     */
    public static Integer getDay(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int day=cal.get(Calendar.DATE);//获取日
        return day;
    }

    /**
     * 格式化Date时间
     * @param time Date类型时间
     * @param timeFromat String类型格式
     * @return 格式化后的字符串
     */
    public static String parseDateToStr(Date time, String timeFromat){
        DateFormat dateFormat=new SimpleDateFormat(timeFromat);
        return dateFormat.format(time);
    }

    /**
     * 格式化Timestamp时间
     * @param timestamp Timestamp类型时间
     * @param timeFromat
     * @return 格式化后的字符串
     */
    public static String parseTimestampToStr(Timestamp timestamp,String timeFromat){
        SimpleDateFormat df = new SimpleDateFormat(timeFromat);
        return df.format(timestamp);
    }

    /**
     * 格式化Date时间
     * @param time Date类型时间
     * @param timeFromat String类型格式
     * @param defaultValue 默认值为当前时间Date
     * @return 格式化后的字符串
     */
    public static String parseDateToStr(Date time, String timeFromat, final Date defaultValue){
        try{
            DateFormat dateFormat=new SimpleDateFormat(timeFromat);
            return dateFormat.format(time);
        }catch (Exception e){
            if(defaultValue!=null)
                return parseDateToStr(defaultValue, timeFromat);
            else
                return parseDateToStr(new Date(), timeFromat);
        }
    }

    /**
     * 格式化Date时间
     * @param time Date类型时间
     * @param timeFromat String类型格式
     * @param defaultValue 默认时间值String类型
     * @return 格式化后的字符串
     */
    public static String parseDateToStr(Date time, String timeFromat, final String defaultValue){
        try{
            DateFormat dateFormat=new SimpleDateFormat(timeFromat);
            return dateFormat.format(time);
        }catch (Exception e){
            return defaultValue;
        }
    }

    /**
     * 格式化String时间
     * @param time String类型时间
     * @param timeFromat String类型格式
     * @return 格式化后的Date日期
     */
    public static Date parseStrToDate(String time, String timeFromat) {
        if (time == null || time.equals("")) {
            return null;
        }

        Date date=null;
        try{
            DateFormat dateFormat=new SimpleDateFormat(timeFromat);
            date=dateFormat.parse(time);
        }catch(Exception e){

        }
        return date;
    }

    /**
     * 格式化String时间
     * @param strTime String类型时间
     * @param timeFromat String类型格式
     * @param defaultValue 异常时返回的默认值
     * @return
     */
    public static Date parseStrToDate(String strTime, String timeFromat,
                                      Date defaultValue) {
        try {
            DateFormat dateFormat = new SimpleDateFormat(timeFromat);
            return dateFormat.parse(strTime);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 当strTime为2008-9时返回为2008-9-1 00:00格式日期时间,无法转换返回null.
     * @param strTime
     * @return
     */
    public static Date strToDate(String strTime) {
        if(strTime==null || strTime.trim().length()<=0)
            return null;

        Date date = null;
        List<String> list = new ArrayList<String>(0);

        list.add(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        list.add(DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS);
        list.add(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI);
        list.add(DATE_TIME_FORMAT_YYYYMMDD_HH_MI);
        list.add(DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        list.add(DATE_FORMAT_YYYY_MM_DD);
        //list.add(DATE_FORMAT_YY_MM_DD);
        list.add(DATE_FORMAT_YYYYMMDD);
        list.add(DATE_FORMAT_YYYY_MM);
        list.add(DATE_FORMAT_YYYYMM);
        list.add(DATE_FORMAT_YYYY);


        for (Iterator iter = list.iterator(); iter.hasNext();) {
            String format = (String) iter.next();
            if(strTime.indexOf("-")>0 && format.indexOf("-")<0)
                continue;
            if(strTime.indexOf("-")<0 && format.indexOf("-")>0)
                continue;
            if(strTime.length()>format.length())
                continue;
            date = parseStrToDate(strTime, format);
            if (date != null)
                break;
        }

        return date;
    }

    /**
     * 解析两个日期之间的所有月份
     * @param beginDateStr 开始日期,至少精确到yyyy-MM
     * @param endDateStr 结束日期,至少精确到yyyy-MM
     * @return yyyy-MM日期集合
     */
    public static List<String> getMonthListOfDate(String beginDateStr, String endDateStr) {
        // 指定要解析的时间格式
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");
        // 返回的月份列表
        String sRet = "";

        // 定义一些变量
        Date beginDate = null;
        Date endDate = null;

        GregorianCalendar beginGC = null;
        GregorianCalendar endGC = null;
        List<String> list = new ArrayList<String>();

        try {
            // 将字符串parse成日期
            beginDate = f.parse(beginDateStr);
            endDate = f.parse(endDateStr);

            // 设置日历
            beginGC = new GregorianCalendar();
            beginGC.setTime(beginDate);

            endGC = new GregorianCalendar();
            endGC.setTime(endDate);

            // 直到两个时间相同
            while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {
                sRet = beginGC.get(Calendar.YEAR) + "-"
                        + (beginGC.get(Calendar.MONTH) + 1);
                list.add(sRet);
                // 以月为单位,增加时间
                beginGC.add(Calendar.MONTH, 1);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析两个日期段之间的所有日期
     * @param beginDateStr 开始日期  ,至少精确到yyyy-MM-dd
     * @param endDateStr 结束日期  ,至少精确到yyyy-MM-dd
     * @return yyyy-MM-dd日期集合
     */
    public static List<String> getDayListOfDate(String beginDateStr, String endDateStr) {
        // 指定要解析的时间格式
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");

        // 定义一些变量
        Date beginDate = null;
        Date endDate = null;

        Calendar beginGC = null;
        Calendar endGC = null;
        List<String> list = new ArrayList<String>();

        try {
            // 将字符串parse成日期
            beginDate = f.parse(beginDateStr);
            endDate = f.parse(endDateStr);

            // 设置日历
            beginGC = Calendar.getInstance();
            beginGC.setTime(beginDate);

            endGC = Calendar.getInstance();
            endGC.setTime(endDate);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // 直到两个时间相同
            while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {

                list.add(sdf.format(beginGC.getTime()));
                // 以日为单位,增加时间
                beginGC.add(Calendar.DAY_OF_MONTH, 1);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当下年份指定前后数量的年份集合
     * @param before 当下年份前年数
     * @param behind 当下年份后年数
     * @return 集合
     */
    public static List<Integer> getYearListOfYears(int before,int behind) {
        if (before<0 || behind<0) {
            return null;
        }
        List<Integer> list = new ArrayList<Integer>();
        Calendar c = null;
        c = Calendar.getInstance();
        c.setTime(new Date());
        int currYear = Calendar.getInstance().get(Calendar.YEAR);

        int startYear = currYear - before;
        int endYear = currYear + behind;
        for (int i = startYear; i < endYear; i++) {
            list.add(Integer.valueOf(i));
        }
        return list;
    }

    /**
     * 获取当前日期是一年中第几周
     * @param date
     * @return
     */
    public static Integer getWeekthOfYear(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setMinimalDaysInFirstWeek(7);
        c.setTime(date);

        return c.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获取某一年各星期的始终时间
     * 实例:getWeekList(2016),第52周(从2016-12-26至2017-01-01)
     * @param year 年份
     * @return
     */
    public static HashMap<Integer,String> getWeekTimeOfYear(int year) {
        HashMap<Integer,String> map = new LinkedHashMap<Integer,String>();
        Calendar c = new GregorianCalendar();
        c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
        int count = getWeekthOfYear(c.getTime());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dayOfWeekStart = "";
        String dayOfWeekEnd = "";
        for (int i = 1; i <= count; i++) {
            dayOfWeekStart = sdf.format(getFirstDayOfWeek(year, i));
            dayOfWeekEnd = sdf.format(getLastDayOfWeek(year, i));
            map.put(Integer.valueOf(i), "第"+i+"周(从"+dayOfWeekStart + "至" + dayOfWeekEnd+")");
        }
        return map;

    }

    /**
     * 获取某一年的总周数
     * @param year
     * @return
     */
    public static Integer getWeekCountOfYear(int year){
        Calendar c = new GregorianCalendar();
        c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
        int count = getWeekthOfYear(c.getTime());
        return count;
    }

    /**
     * 获取指定日期所在周的第一天
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
        return c.getTime();
    }

    /**
     * 获取指定日期所在周的最后一天
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
        return c.getTime();
    }

    /**
     * 获取某年某周的第一天
     * @param year 目标年份
     * @param week 目标周数
     * @return
     */
    public static Date getFirstDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getFirstDayOfWeek(cal.getTime());
    }

    /**
     * 获取某年某周的最后一天
     * @param year 目标年份
     * @param week 目标周数
     * @return
     */
    public static Date getLastDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getLastDayOfWeek(cal.getTime());
    }

    /**
     * 获取某年某月的第一天
     * @param year 目标年份
     * @param month 目标月份
     * @return
     */
    public static Date getFirstDayOfMonth(int year,int month){
        month = month-1;
        Calendar   c   =   Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);

        int day = c.getActualMinimum(c.DAY_OF_MONTH);

        c.set(Calendar.DAY_OF_MONTH, day);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * 获取某年某月的最后一天
     * @param year 目标年份
     * @param month 目标月份
     * @return
     */
    public static Date getLastDayOfMonth(int year,int month){
        month = month-1;
        Calendar   c   =   Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        int day = c.getActualMaximum(c.DAY_OF_MONTH);
        c.set(Calendar.DAY_OF_MONTH, day);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return c.getTime();
    }

    /**
     * 获取某个日期为星期几
     * @param date
     * @return String "星期*"
     */
    public static String getDayWeekOfDate1(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    /**
     * 获得指定日期的星期几数
     * @param date
     * @return int
     */
    public static Integer getDayWeekOfDate2(Date date){
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(date);
        int weekDay = aCalendar.get(Calendar.DAY_OF_WEEK);
        return weekDay;
    }

    /**
     * 验证字符串是否为日期
     * 验证格式:YYYYMMDD、YYYY_MM_DD、YYYYMMDDHHMISS、YYYYMMDD_HH_MI、YYYY_MM_DD_HH_MI、YYYYMMDDHHMISSSSS、YYYY_MM_DD_HH_MI_SS
     * @param strTime
     * @return null时返回false;true为日期,false不为日期
     */
    public static boolean validateIsDate(String strTime) {
        if (strTime == null || strTime.trim().length() <= 0)
            return false;

        Date date = null;
        List<String> list = new ArrayList<String>(0);

        list.add(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        list.add(DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS);
        list.add(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI);
        list.add(DATE_TIME_FORMAT_YYYYMMDD_HH_MI);
        list.add(DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        list.add(DATE_FORMAT_YYYY_MM_DD);
        //list.add(DATE_FORMAT_YY_MM_DD);
        list.add(DATE_FORMAT_YYYYMMDD);
        //list.add(DATE_FORMAT_YYYY_MM);
        //list.add(DATE_FORMAT_YYYYMM);
        //list.add(DATE_FORMAT_YYYY);

        for (Iterator iter = list.iterator(); iter.hasNext();) {
            String format = (String) iter.next();
            if(strTime.indexOf("-")>0 && format.indexOf("-")<0)
                continue;
            if(strTime.indexOf("-")<0 && format.indexOf("-")>0)
                continue;
            if(strTime.length()>format.length())
                continue;
            date = parseStrToDate(strTime.trim(), format);
            if (date != null)
                break;
        }

        if (date != null) {
            System.out.println("生成的日期:"+DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, "--null--"));
            return true;
        }
        return false;
    }

    /**
     * 将指定日期的时分秒格式为零
     * @param date
     * @return
     */
    public static Date formatHhMmSsOfDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获得指定时间加减参数后的日期(不计算则输入0)
     * @param date 指定日期
     * @param year 年数,可正可负
     * @param month 月数,可正可负
     * @param day 天数,可正可负
     * @param hour 小时数,可正可负
     * @param minute 分钟数,可正可负
     * @param second 秒数,可正可负
     * @param millisecond 毫秒数,可正可负
     * @return 计算后的日期
     */
    public static Date addDate(Date date,int year,int month,int day,int hour,int minute,int second,int millisecond){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, year);//加减年数
        c.add(Calendar.MONTH, month);//加减月数
        c.add(Calendar.DATE, day);//加减天数
        c.add(Calendar.HOUR,hour);//加减小时数
        c.add(Calendar.MINUTE, minute);//加减分钟数
        c.add(Calendar.SECOND, second);//加减秒
        c.add(Calendar.MILLISECOND, millisecond);//加减毫秒数

        return c.getTime();
    }

    /**
     * 获得两个日期的时间戳之差
     * @param startDate
     * @param endDate
     * @return
     */
    public static Long getDistanceTimestamp(Date startDate,Date endDate){
        long daysBetween=(endDate.getTime()-startDate.getTime()+1000000)/(3600*24*1000);
        return daysBetween;
    }

    /**
     * 判断二个时间是否为同年同月
     * @param date1
     * @param date2
     * @return
     */
    public static Boolean compareIsSameMonth(Date date1,Date date2){
        boolean flag = false;
        int year1  = getYear(date1);
        int year2 = getYear(date2);
        if(year1 == year2){
            int month1 = getMonth(date1);
            int month2 = getMonth(date2);
            if(month1 == month2)flag = true;
        }
        return flag;
    }

    /**
     * 获得两个时间相差距离多少天多少小时多少分多少秒
     * @param one 时间参数 1 格式:1990-01-01 12:00:00
     * @param two 时间参数 2 格式:2009-01-01 12:00:00
     * @return long[] 返回值为:{天, 时, 分, 秒}
     */
    public static long[] getDistanceTime(Date one, Date two) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {

            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long[] times = {day, hour, min, sec};
        return times;
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式:1990-01-01 12:00:00
     * @param str2 时间参数 2 格式:2009-01-01 12:00:00
     * @return String 返回值为:{天, 时, 分, 秒}
     */
    public static long[] getDistanceTime(String str1, String str2) {
        DateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long[] times = {day, hour, min, sec};
        return times;
    }

    /**
     * 两个时间之间相差距离多少天
     * @param str1 时间参数 1:
     * @param str2 时间参数 2:
     * @return 相差天数
     */
    public static Long getDistanceDays(String str1, String str2) throws Exception{
        DateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        Date one;
        Date two;
        long days=0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 获取指定时间的那天 00:00:00.000 的时间
     * @param date
     * @return
     */
    public static Date getDayBeginTime(final Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * 获取指定时间的那天 23:59:59.999 的时间
     * @param date
     * @return
     */
    public static Date getDayEndTime(final Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return c.getTime();
    }

 /*
    public static void main(String [] args){
        try {
            DateUtil dateUtil = new DateUtil();
            System.out.println();

        } catch (Exception e) {
            // TODO: handle exception
        }

    }  */

}

5、FileUtil

package com.aura.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
    private static final String WIN_NEW_LINE = "\r\n";     //windows


    /**
     * 获取reader对象,可以读文件。
     * @param filePath 读取的文件的路径及名称
     * @param encode 读取的文件的编码格式
     * @return reader对象
     */
    public static BufferedReader getReader(String filePath,String encode){
        BufferedReader reader = null;
        try {
            File filename = new File(filePath);
            if(!filename.exists()) {
                throw new FileNotFoundException(filePath+"file is not Found");
            }
            FileInputStream fileInputStream = new FileInputStream(filename);
            reader = new BufferedReader(new InputStreamReader(fileInputStream, encode));
        } catch(IOException e) {
            LOGGER.error("read file failure",e);
        }
        return reader;
    }

    /**
     * 获取reader对象,可以读文件。
     * @param filePath 读取的文件的路径及名称
     * @return reader对象
     */
    public static BufferedReader getReader(String filePath){
        return getReader(filePath,"utf-8");
    }


    /**
     * 获取得到写文件对象
     * @param writerFilePath 写出的文件的路径和保存的文件名
     * @param isAppend true:追加的方式保存,false:直接覆盖的方式保存
     * @return 写文件对象
     */
    public static BufferedWriter getWriter(String writerFilePath,Boolean isAppend){
        BufferedWriter writer = null;
        try {
            File writeFileName = new File(writerFilePath); // 相对路径,如果没有则要建立一个新的output.txt文件
            if(!writeFileName.exists()) {
                writeFileName.createNewFile(); // 创建新文件
            }
            //FileWriter fileWriter = new FileWriter(writeFileName);
            FileWriter fileWriter = new FileWriter(writeFileName,isAppend);     //true,代表着追加写入,不会讲之前已经录入的内容覆盖
            writer = new BufferedWriter(fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer;
    }

    /**
     * 获取得到写文件对象
     * @param writerFilePath 写出的文件的路径和保存的文件名
     * @return 写文件对象,默认是覆盖方式
     */
    public static BufferedWriter getWriter(String writerFilePath){
        return getWriter(writerFilePath,false);
    }


    /**
     * 写入文件,末尾自动添加\r\n
     * utf-8  追加
     * @param writerFilePath
     * @param context 要往文件写入的内容
     * @param isAppend 是否是将context内容追加到制定文件的末尾?true:追加。false:覆盖。默认是false。
     */
    public static void writeFile(String writerFilePath, String context,Boolean isAppend) {
        BufferedWriter writer = getWriter(writerFilePath,isAppend);
        StringBuffer buffer = new StringBuffer();
        buffer.append(context + WIN_NEW_LINE);
        try {
            writer.write(buffer.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入文件,末尾自动添加\r\n
     * utf-8  追加
     * @param writerFilePath
     * @param context 要往文件写入的内容
     */
    public static void writeFile(String writerFilePath, String context) {
        writeFile(writerFilePath,context,false);
    }


    /**
     * 加入编码
     * 整个文件以string放回,添加\r\n换行
     * @param filePath 读取的文件的路径及名称
     * @param encode 读取的文件的编码格式
     * @return 返回的是所有行的String类型的字符串
     */
    public static String readfileToString(String filePath,String encode) {
        StringBuffer sb=new StringBuffer();
        String line=null;
        BufferedReader reader = getReader(filePath,encode);
        try {
            while((line=reader.readLine())!=null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 整个文件以string放回,添加\r\n换行
     * @param filePath 读取的文件的路径及名称
     * @return 返回的是所有行的String类型的字符串
     */
    public static String readfileToString(String filePath) {
        return readfileToString(filePath,"utf-8");
    }



    /**
     * 按行读取文件,以list<String>的形式返回
     * @param filePath 读取文件的路劲及名称
     * @return 返回的是每行内容的list集合
     */
    public static List<String> readFileToList(String filePath,String encode) {
        List<String> lines = new ArrayList<String>();     //lines:文件所有行的数据
        String line = null;                               //line:一次读入一行的数据
        BufferedReader reader = getReader(filePath,encode);
        //line:一次读入一行的数据
        try {
            while((line = reader.readLine()) != null) {
                lines.add(line.toString());
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    /**
     * 按行读取文件,以list<String>的形式返回
     * @param filePath 读取文件的路劲及名称
     * @return 返回的是每行内容的list集合
     */
    public static List<String> readFileToList(String filePath) {
        return readFileToList(filePath,"utf-8");
    }


    /**
     * 创建目录
     * @param dirPath 所要创建的目录字符串
     */
    public static boolean mkDir(String dirPath) {
        File file = new File(dirPath);
        return file.mkdirs();
    }

    /**
     * 创建文件
     * @param filePath
     */
    public static boolean touch(String filePath) {
        File file = new File(filePath);
        boolean success = false;
        try {
            if (!file.exists()) {
                success = file.createNewFile();
            }
        }
        catch (Exception e) {
            LOGGER.error("新建文件操作出错",e);
        }
        return success;
    }

    /**
     * 递归删除文件或者目录
     * @param filePath
     */
    public static void deleteEveryThing(String filePath) {
        try{
            File file=new File(filePath);
            if(!file.exists()){
                return ;
            }
            if(file.isFile()){
                file.delete();
            }else{
                File[] files = file.listFiles();
                for(int i=0;i<files.length;i++){
                    String root=files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
                    deleteEveryThing(root);
                }
                file.delete();
            }
        } catch(Exception e) {
            LOGGER.error("删除文件失败",e);
        }
    }

    /**
     *
     * @param filePath
     * @return ture:文件存在。false:文件不存在。
     */
    public static boolean fileIsExists(String filePath){
        File file=new File(filePath);
        return file.exists();
    }

    /*
     * 得到一个文件夹下所有文件
     */
    public static List<String> getAllFileNameInFold(String fold_path) {
        List<String> file_paths = new ArrayList<String>();

        LinkedList<String> folderList = new LinkedList<String>();
        folderList.add(fold_path);
        while (folderList.size() > 0) {
            File file = new File(folderList.peekLast());
            folderList.removeLast();
            File[] files = file.listFiles();
            ArrayList<File> fileList = new ArrayList<File>();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    folderList.add(files[i].getPath());
                } else {
                    fileList.add(files[i]);
                }
            }
            for (File f : fileList) {
                file_paths.add(f.getAbsoluteFile().getPath());
            }
        }
        return file_paths;
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值