java工具类大全

1.发送类。

package cn.fx.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiUtil {

	public static String send(String request, String url) throws UnsupportedEncodingException {
		HttpURLConnection httpURLConnection = null;
		OutputStreamWriter outputStreamWriter = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		String resposnse = "";
		try {
			httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
			httpURLConnection.setConnectTimeout(100000);
			httpURLConnection.setReadTimeout(100000);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setAllowUserInteraction(true);
			httpURLConnection.connect();
			outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
			outputStreamWriter.write(request);
			outputStreamWriter.flush();
			outputStreamWriter.close();
			inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
			bufferedReader = new BufferedReader(inputStreamReader);
			do {
				resposnse = bufferedReader.readLine();
			} while (bufferedReader.read() != -1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resposnse;
	}

}

2.DateUtil日期工具类

(1)需要导入的包

主要用于Strings.isNullOrEmpty(date)

<!--string处理类-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.0.1-jre</version>
 </dependency>

(2)DateUtil类

import com.google.common.base.Strings;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 功能描述:日期工具
 *
 */
public class DateUtil {
    /** yyyy-MM-dd */
    public static String YYYYMMDD = "yyyy-MM-dd";
    /** yyyyMMdd */
    public static String yyyyMMdd = "yyyyMMdd";
    /** yyyyMMddHHmmss */
    public static String yyyyMMddHHmmss = "yyyyMMddHHmmss";
    /** yyyy-MM-dd HH:mm:ss **/
    public static String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";

    public static String DDMMMYYYY = "ddMMMyyyy";
    public static String yyyyMMddHHmm = "yyyy-MM-dd HH:mm";

    /**
     * 返回当前时间字符串 YYYYMMDDHHMMSS
     * 
     * @return
     */
    public static String getNow() {
        return format(new Date(), YYYYMMDDHHMMSS);
    }
    
    public static String getNow(String format) {
        return format(new Date(), format);
    }

    public static Date getToday() {
        Calendar now = Calendar.getInstance();
        return getYYYYMMDD(format(now.getTime(), YYYYMMDD));
    }

    /**
     * <p>
     * Description:将字符串转化为日期
     * </p>
     * 
     * @param dateString
     *            日期字符串
     * @return yyyy-MM-dd
     * @throws Exception
     */
    public static Date getYYYYMMDD(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDD);
        Date dateTime = null;
        try {
            dateTime = dateFormat.parse(dateString);
        } catch (ParseException e) {
            dateTime = null;
        } // END TRY
        return dateTime;
    }

    public static Date getYYYYMMDDHHMMSS(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDDHHMMSS);
        Date dateTime = null;
        try {
            dateTime = dateFormat.parse(dateString);
        } catch (ParseException e) {
            dateTime = null;
        } // END TRY
        return dateTime;
    }

    public static Date stringtoDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDDHHMMSS);
        Long time=new Long(dateString);
        String d = dateFormat.format(time);
        Date date = null;
        try {
            date = dateFormat.parse(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    
    /**
     * Get Date from String "yyyy-MM-dd HH:mm"
     * 
     * @param dateString
     * @return
     */
    public static Date getYYYYMMDDHHmm(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(yyyyMMddHHmm);
        Date dateTime = null;
        try {
            dateTime = dateFormat.parse(dateString);
        } catch (ParseException e) {
            dateTime = null;
        } // END TRY
        return dateTime;
    }

    /**
     * 得到當前日期為周幾
     * 
     * @param date
     * @return
     */
    public static int dayOfWeek(Date date) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(date);
        int x = aCalendar.get(Calendar.DAY_OF_WEEK);
        return x;
    }

    /**
     * 得到當前日期為周幾
     * 
     * @param date
     * @return
     */
    public static String getWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }

    /**
     * 得到几天前的时间
     */

    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    /**
     * 返回字符型日期时间
     * 
     * @param date
     *            日期
     * @return 返回字符型日期时间
     */
    public static String getDateTime(Date date) {
        return format(date, "yyyy-MM-dd HH:mm:ss");
    }


    /**
     * 返回字符型日期时间
     *
     * @param date
     *            日期
     * @return 返回字符型日期时间
     */
    public static String getDateTime(Date date ,String format) {
        return format(date, format);
    }

    /**
     * 格式化输出日期
     *
     * @param date
     *            日期
     * @param format
     *            格式
     * @return 返回字符型日期
     */
    public static String format(Date date, String format) {
        String result = "";
        try {
            if (date != null) {
                java.text.DateFormat df = new SimpleDateFormat(format);
                result = df.format(date);
            }
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 将日期类型格式化为字符串
     *
     * @param date
     *            yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String format(Date date) {
        return format(date, YYYYMMDDHHMMSS);
    }

    public static String format(Long millis) {
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis(millis);
        return format(now.getTime(), YYYYMMDDHHMMSS);
    }

    /**
     * 得到几天后的时间
     */

    public static Date getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

    /**
     * 得到几天后的时间
     */
    public static String getDateAfter(String d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(formatDate(d, DateUtil.YYYYMMDD));
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return format(now.getTime(), DateUtil.YYYYMMDD);
    }

    /**
     * 得到几天后的时间
     */
    public static String getDateAfter(String d, String format, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(formatDate(d, format));
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return format(now.getTime(), format);
    }

    /**
     * @description: 根据日期,类型,数值得到加减后的日期
     * @param date
     *            日期
     * @param type
     *            类型,为year,month,day,hour.....
     * @param amount
     *            时间加减的数值
     * @return:
     */
    public static Date getDateAdd(Date date, String type, int amount) {
        if (date == null) {
            return date;
        } else {
            Calendar now = Calendar.getInstance();
            now.setTime(date);
            if ("year".equalsIgnoreCase(type)) {
                now.add(Calendar.YEAR, amount);
            } else if ("month".equalsIgnoreCase(type)) {
                now.add(Calendar.MONTH, amount);
            } else if ("day".equalsIgnoreCase(type)) {
                now.add(Calendar.DATE, amount);
            } else if ("hour".equalsIgnoreCase(type)) {
                now.add(Calendar.HOUR_OF_DAY, amount);
            } else if ("minute".equalsIgnoreCase(type)) {
                now.add(Calendar.MINUTE, amount);
            } else if ("second".equalsIgnoreCase(type)) {
                now.add(Calendar.SECOND, amount);
            } else if ("millsecond".equalsIgnoreCase(type)) {
                now.add(Calendar.MILLISECOND, amount);
            }
            return now.getTime();
        }
    }

    /**
     * 两个时间之间的天数
     *
     * @param date1
     * @param date2
     * @return
     * @throws ParseException
     */
    public static long getDays(String date1, String date2) throws ParseException {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat(YYYYMMDD);
        Date date = null;
        Date mydate = null;
        date = myFormatter.parse(date1);
        mydate = myFormatter.parse(date2);
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    public static long getHours(Date date1, Date date2) {
        if (date1 == null)
            return 0;
        if (date2 == null)
            return 0;

        long hours = (date1.getTime() - date2.getTime()) / (60 * 60 * 1000);
        return hours;
    }

    public static long getMins(Date date1, Date date2) {
        if (date1 == null)
            return 0;
        if (date2 == null)
            return 0;

        long mins = (date1.getTime() - date2.getTime()) / (60 * 1000);
        return mins;
    }

    /**
     * 两个时间之间的天数
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static long getDays(Date date1, Date date2) {
        if (date1 == null)
            return 0;
        if (date2 == null)
            return 0;

        long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 格式化日期
     * 
     * @param date
     * @return
     */
    public static Date formatDate(String date) {
        Date d = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            d = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }

    /**
     * 按指定格式格式化日期
     * 
     * @param date
     * @param format
     * @return
     */
    public static Date formatDate(String date, String format) {
        Date d = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            d = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }

    /**
     * 将yyyy-MM-dd时间格式转换成ddMMMyy
     * 
     * @param dateString
     * @return
     */
    public static String stringToDateddMMMyy(String dateString) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
        try {

            Date dateTime = sf.parse(dateString);
            dateString = sdf.format(dateTime);
        } catch (ParseException e) {

            throw new RuntimeException("Not a date!");
        }
        return dateString;
    }

    /**
     * 将ddMMMyy时间格式转换成yyyy-MM-dd
     * 
     * @param dateString
     * @return
     */
    public static String ddMMMyyToYYYYMMDD(String dateString) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
        try {

            Date dateTime = sdf.parse(dateString);
            dateString = sf.format(dateTime);
        } catch (ParseException e) {

            throw new RuntimeException("Not a date!");
        }
        return dateString;
    }

    /**
     * 将yyyy-MM-dd时间格式转换成MMMyy
     * 
     * @param dateString
     * @return
     */
    public static String stringToDateMMMyy(String dateString) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("MMMyy", Locale.US);
        try {

            Date dateTime = sf.parse(dateString);
            dateString = sdf.format(dateTime);
        } catch (ParseException e) {

            throw new RuntimeException("Not a date!");
        }
        return dateString;
    }

    /**
     * 将时间格式转换成ddMMMyy
     * 
     * @param date
     * @return
     */
    public static String dateToDateddMMMyy(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
        String dateString = sdf.format(date);
        return dateString;
    }

    /**
     * ddMMMyy时间格式转为Date
     * 
     * @param dateString
     * @return
     */
    public static Date ddMMMyyToDate(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 将时间格式转换成ddMMM
     * 
     * @param date
     * @return
     */
    public static String dateToDateddMMM(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat("ddMMM", Locale.US);
        String dateString = sdf.format(date);
        return dateString;
    }

    /**
     * ddMMMyyHHmm时间格式转为Date
     * 
     * @param dateString
     * @return
     */
    public static Date ddMMMyyHHmmToDate(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyHHmm", Locale.US);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * ddMMMyyyyHHmm时间格式转为Date
     * 
     * @param dateString
     * @return
     */
    public static Date ddMMMyyyyHHmmToDate(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyyHHmm", Locale.US);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 计算某个日期的前n天
     * 
     * @param date
     * @param count
     * @return
     */
    public static Date getCountDate(Date date, int count) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        long timeCount = c.getTimeInMillis() - count * 1000 * 60 * 60 * 24;// .getTime().getTime();
        c.setTimeInMillis(timeCount);
        return c.getTime();
    }

    /**
     * 计算某个日期与当天的相差天数
     * 
     * @param date1
     * @return
     */
    public static int countDays(Date date1) {
        Calendar c = Calendar.getInstance();
        Calendar c1 = Calendar.getInstance();
        c.setTime(date1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c1.setTime(new Date());
        c1.set(Calendar.HOUR, 0);
        c1.set(Calendar.MINUTE, 0);
        c1.set(Calendar.SECOND, 0);
        long count = c.getTimeInMillis() - c1.getTimeInMillis();
        int day = (int) Math.ceil(count / 86400000);
        return day;
    }

    public static final Pattern eeDDMMyy = Pattern.compile("^([a-zA-Z]{2})([0-9]{2}[a-zA-Z]{3})([0-9]{2})$");
    public static final Pattern eeDDMMM = Pattern.compile("^([a-zA-Z]{2})([0-9]{2}[a-zA-Z]{3})$");
    public static final Pattern ddMMM = Pattern.compile("^([0-9]{2})([a-zA-Z]{3})$");
    public static final Pattern ddMMMyy = Pattern.compile("^([0-9]{2})([a-zA-Z]{3})([0-9]{2})$");

    /**
     * 解析黑屏PNR返回的日期格式 解析规则:默认使用当前年份,若得到的日期中星期与PNR中星期不对应 则使用下一年和上一年的年份,否则返回null
     * 
     * @param pnrDateStr
     *            必须是 Th25OCT 或者Th25OCT13 或者 ddMMM ddMMMyy 格式
     * @return 格式不满足条件则返回null
     */
    public static Date parseDateFormPnr(String pnrDateStr) {
        if (pnrDateStr == null || pnrDateStr.isEmpty()) {
            return null;
        }

        Matcher matchereeDDMMM = eeDDMMM.matcher(pnrDateStr);
        Matcher matchereeDDMMMyy = eeDDMMyy.matcher(pnrDateStr);
        Matcher matcherddMMM = ddMMM.matcher(pnrDateStr);
        Matcher matcherddMMMyy = ddMMMyy.matcher(pnrDateStr);
        // 匹配EEDDMMM
        if (matchereeDDMMM.matches()) {
            String week = matchereeDDMMM.group(1);

            Calendar calendar = Calendar.getInstance();
            String ddmmmyyyyStr = matchereeDDMMM.group(2) + calendar.get(Calendar.YEAR);
            SimpleDateFormat sdf = new SimpleDateFormat(DDMMMYYYY, Locale.US);
            Date date;
            try {
                date = sdf.parse(ddmmmyyyyStr);
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
            calendar.setTime(date);

            int calendarWeek = parseDayOfWeek(week);
            if (calendar.get(Calendar.DAY_OF_WEEK) == calendarWeek) {
                return date;
            } else {
                calendar.add(Calendar.YEAR, 1);
                if (calendar.get(Calendar.DAY_OF_WEEK) == calendarWeek) {
                    return calendar.getTime();
                } else {
                    calendar.add(Calendar.YEAR, -2);
                    if (calendar.get(Calendar.DAY_OF_WEEK) == calendarWeek) {
                        return calendar.getTime();
                    } else {
                        return null;
                    }
                }
            }

        }
        // 匹配EEDDMMMyy
        if (matchereeDDMMMyy.matches()) {

            String ddmmmyyStr = matchereeDDMMMyy.group(2) + matchereeDDMMMyy.group(3);

            SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
            Date date;
            try {
                date = sdf.parse(ddmmmyyStr);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 匹配DDMMM
        if (matcherddMMM.matches()) {

            String ddmmmyyStr = pnrDateStr;
            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMM", Locale.US);
            Date date;
            try {
                int year = c.get(Calendar.YEAR);
                date = sdf.parse(ddmmmyyStr);
                c.setTime(date);
                c.set(Calendar.YEAR, year);
                return c.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 匹配ddMMMyy
        if (matcherddMMMyy.matches()) {

            String ddmmmyyStr = pnrDateStr;
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy", Locale.US);
            Date date;
            try {

                date = sdf.parse(ddmmmyyStr);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 转化为 yyyy-MM-dd格式
     * 
     * @param pnrDateStr
     * @return
     */
    public static String formatDateFormPnr(String pnrDateStr) {
        Date date = parseDateFormPnr(pnrDateStr);
        if (date != null) {
            return format(date, "yyyy-MM-dd");
        }
        return null;
    }

    /**
     * 转化为 黑屏返回的HHmm格式航班日期
     * 
     * @param pnrTimeStr
     *            格式:四位 0900
     * @return
     */
    public static String formatTimeFormPnr(String pnrTimeStr) {
        if (pnrTimeStr == null || pnrTimeStr.length() != 4) {
            return null;
        }
        return pnrTimeStr.substring(0, 2) + ":" + pnrTimeStr.substring(2, 4);
    }

    /**
     * 格式化pnr 起飞达到时间
     * 
     * @param flightDate
     *            pnr航班日期字符串
     * @param time
     *            pnr起飞或到达时间字符串
     * @return yyyy-MM-dd HH:ss OR ""
     */
    public static String formatDateTimeFormPnr(String flightDate, String time) {
        String date = formatDateFormPnr(flightDate);
        if (!Strings.isNullOrEmpty(date) && time.length() >= 4) {
            int index = time.indexOf("+1");
            if (index >= 0) {
                time = time.substring(0, index);
                date = getDateAfter(date, 1);
            }
            time = time.substring(0, 2) + ":" + time.substring(2, 4);
            return date + " " + time;
        } else {
            return "";
        }
    }




    /**
     * 获取经停分钟数
     * 
     * @return
     */
    public static int getStopMins(String arriveTime, String departTime) {
        if (!Strings.isNullOrEmpty(arriveTime) && arriveTime.length() >= 4 && !Strings.isNullOrEmpty(departTime)
                && departTime.length() >= 4) {
            int arriveHour = Integer.parseInt(arriveTime.substring(0, 2));
            int arriveMin = Integer.parseInt(arriveTime.substring(2, 4));
            int departHour = Integer.parseInt(departTime.substring(0, 2));
            int departMin = Integer.parseInt(departTime.substring(2, 4));
            return ((departHour - arriveHour) * 60) + (departMin - arriveMin);
        }
        return 0;
    }

    /**
     * @Title: getBeforDay @Description: 获取当前时间的前一天 @param @param
     * date @param @return @return Date @throws
     */

    public static String getBeforOneDay(Date date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String dateStr = formatDate(date, format);
        try {
            date = dateFormat.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, -1);
            date = calendar.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr = formatDate(date, format);
    }

    /**
     * 把字符串格式化成日期
     * 
     * @param argDateStr
     * @param argFormat
     * @return
     */
    public static Date formatStringToDate(String argDateStr, String argFormat) {
        if (argDateStr == null || argDateStr.trim().length() < 1) {
            return null;
        }

        SimpleDateFormat sdfFormat = null;
        Date result = null;

        try {
            String strFormat = argFormat;
            if (Strings.isNullOrEmpty(strFormat)) {
                strFormat = yyyyMMdd;
                if (argDateStr.length() > 16) {
                    strFormat = YYYYMMDDHHMMSS;
                } else if (argDateStr.length() > 10) {
                    strFormat = yyyyMMddHHmm;
                }
            }
            sdfFormat = new SimpleDateFormat(strFormat);
            result = sdfFormat.parse(argDateStr);
        } catch (Exception e) {
            result = null;
        } finally {
            sdfFormat = null;
        }

        return result;
    }

    /**
     * 格式化日期格式
     * 
     * @param argDate
     * @param argFormat
     * @return 格式化后的日期字符串
     */
    public static String formatDate(Date argDate, String argFormat) {
        if (argDate == null) {
            return "";
        }
        SimpleDateFormat sdfFrom = null;
        String strResult = null;

        try {
            sdfFrom = new SimpleDateFormat(argFormat);
            strResult = sdfFrom.format(argDate).toString();
        } catch (Exception e) {
            strResult = "";
        } finally {
            sdfFrom = null;
        }
        return strResult;
    }

    // 获取当天时间的前n天时间
    public static Date getBeforDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -day);
        date = calendar.getTime();
        return date;
    }
    
    //两分钟后
    public static Long getAfterTwoMinute() {
        Calendar canlendar = Calendar.getInstance(); // java.util包
        Long current = canlendar.getTimeInMillis();
        canlendar.add(Calendar.MINUTE, 2); 
        Long after = canlendar.getTimeInMillis();
        return after;
    }

    public static void main(String[] args) {
        /*
         * SimpleDateFormat sdf = new SimpleDateFormat("ddMMM", Locale.US);
         * System.out.println(sdf.format(new Date()).toUpperCase());
         */
        /*
         * System.out.println(parseDateFormPnr("TU23APR"));
         * System.out.println(parseDateFormPnr("WE23APR14"));
         * System.out.println(parseDateFormPnr("23APR"));
         * System.out.println(parseDateFormPnr("23APR13"));
         */
        // System.out.println(getBeforDay(new Date(),"yyyy-MM-dd"));
        // System.out.println( getBeforOneDay( new Date(), "yyyy-MM-dd" ) );
//      SimpleDateFormat fomat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ms");
//      System.out.println(fomat.format(getToday()));
        
        System.out.println(DateUtil.stringtoDate("1445839889"));

    }

    /**
     * 计算并格式化消耗时间<br>
     * generate by: vakin jiang at 2012-2-16
     * 
     * @param startPoint
     * @return
     */
    public static String formatTimeConsumingInfo(long startPoint) {
        StringBuffer buff = new StringBuffer();
        long totalMilTimes = System.currentTimeMillis() - startPoint;
        int mi = (int) Math.floor(totalMilTimes / 60000);
        int se = (int) Math.floor((totalMilTimes - 60000 * mi) / 1000);
        if (mi > 0)
            buff.append(mi).append("mins ");
        buff.append(se).append("s");
        return buff.toString();
    }
    
    
    /**
     * 得到當前日期的前一个月
     * 
     * @return
     */
    public static String getLastMonth() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        SimpleDateFormat format =  new SimpleDateFormat("yyyyMM");
        String time = format.format(c.getTime());
        return time;
    }


}

3.常用业务返回对象类ResponseJson

import java.io.Serializable;

public class ResponseJson implements Serializable {

    private static final long serialVersionUID = 1L;
    public ResultCode resultCode; // 业务响应码
    public String resultMsg = ""; // 返回信息描述
    public String errCode; // 错误代码
    public String errCodeDes = ""; // 错误代码
    public Object data; // 返回业务参数

    public ResponseJson(ResultCode resultCode, String resultMsg, Object data) {
        super();
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
        this.data = data;
    }

    public ResponseJson(ResultCode resultCode, ErrorCode errCode, Object data) {
        super();
        this.resultCode = resultCode;
        this.errCode = errCode.getName();
        this.errCodeDes = errCode.getDes();
        this.resultMsg = errCode.getDes();
        this.data = data;
    }

    public ResponseJson(ResultCode resultCode, Object data) {
        super();
        this.resultCode = resultCode;
        this.data = data;
    }

    public ResponseJson(ResultCode resultCode, ErrorCode errCode) {
        super();
        this.resultCode = resultCode;
        this.errCode = errCode.getName();
        this.errCodeDes = errCode.getName();
        this.resultMsg = errCode.getDes();
    }


    public ResponseJson(ResultCode resultCode) {
        super();
        this.resultCode = resultCode;
    }

    public ResponseJson(ResultCode resultCode, ErrorCode errCode, String errCodeDes) {
        super();
        this.resultCode = resultCode;
        this.errCode = errCode.getName();
        this.errCodeDes = errCodeDes;
        this.resultMsg = errCodeDes;
    }

    public enum ResultCode {
        SUCCESS, // 业务处理成功
        FAIL; // 业务处理失败
    }
    
    //可根据自己的写
    public enum ErrorCode {
        VALIDATE_ERROR("VALIDATE_ERROR", "校验异常"),
        ORDER_IS_NOTEXIST("ORDER_IS_NOTEXIST","订单不存在");

        private String name;
        private String des;

        // 构造方法
        ErrorCode(String name, String des) {
            this.name = name;
            this.des = des;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDes() {
            return des;
        }

        public void setDes(String des) {
            this.des = des;
        }

    }

    public ResultCode getResultCode() {
        return resultCode;
    }

    public void setResultCode(ResultCode resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultMsg() {
        return resultMsg;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }

    public String getErrCode() {
        return errCode;
    }

    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }

    public String getErrCodeDes() {
        return errCodeDes;
    }

    public void setErrCodeDes(String errCodeDes) {
        this.errCodeDes = errCodeDes;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}

3.MD5加密Util

(1)需要导入的包

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>

(2)MD5Util类

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


public class MD5Util {

    /**
     * 字符串签名
     * @param text    需要签名的字符串
     * @param key     密钥
     * @param charset 编码格式
     * @return 签名结果
     */
    public static String sign(String text, String key, String charset) {
        //拼接key
        text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, charset));
    }

    /**
     * 根据参数map签名
     * @param map 有序map
     * @param key
     * @param charset
     * @return
     */
    public static String sign(TreeMap<String, Object> map, String key, String charset){
        Set<String> keySet = map.keySet();
        StringBuilder sb = new StringBuilder();
        for (String mapKey : keySet){
            String value = (String)map.get(key);
            sb.append(key).append("=").append(value).append("&");
        }
        return sign(sb.toString(), key, charset);
    }


    /**
     * 根据参数map签名
     * @param map hashMap
     * @param key
     * @param charset
     * @return
     */
    public static String sign1(Map<String, Object> map, String key, String charset){
        Set<String> keySet = map.keySet();
        StringBuilder sb = new StringBuilder();
        for (String mapKey : keySet){
            String value = (String)map.get(key);
            sb.append(key).append("=").append(value).append("&");
        }
        return sign(sb.toString(), key, charset);
    }

    /**
     * 根据参数map签名
     * @param map hashMap
     * @param key
     * @param charset
     * @return
     */
    public static String sign(Map<String, String> map, String key, String charset){
        Set<String> keySet = map.keySet();
        StringBuilder sb = new StringBuilder();
        for (String mapKey : keySet){
            String value = (String)map.get(key);
            sb.append(key).append("=").append(value).append("&");
        }
        return sign(sb.toString(), key, charset);
    }

    /**
     * 根据字符串获取byte[]
     * @param content
     * @param charset
     * @return
     */
    private static byte[] getContentBytes(String content, String charset){
        if (StringUtils.isEmpty(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("转码过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 签名,不用加密码
     * @param origin
     * @param charsetname
     * @return
     */
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }
    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;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };


}

4.永不重复的id生成器

(1)需要导入的包

主要用在格式化日FastDateFormat.getInstance("yyyyMMddHHmmssSSS");

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

(2)IdGenerator类

import org.apache.commons.lang3.time.FastDateFormat;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 与snowflake算法区别,返回字符串id,占用更多字节,但直观从id中看出生成时间
 * 改写了生成时间的format方法
 * @Project concurrency
 */

public enum IdGenerator {

    INSTANCE;
    private long workerId;   //用ip地址最后几个字节标示
    private long datacenterId = 0L; //可配置在properties中,启动时加载,此处默认先写成0
    private long sequence = 0L;
    private long workerIdBits = 8L; //节点ID长度
    private long datacenterIdBits = 2L; //数据中心ID长度,可根据时间情况设定位数
    private long sequenceBits = 12L; //序列号12位
    private long workerIdShift = sequenceBits; //机器节点左移12位
    private long datacenterIdShift = sequenceBits + workerIdBits; //数据中心节点左移14位
    private long sequenceMask = -1L ^ (-1L << sequenceBits); //4095
    private long lastTimestamp = -1L;
    private static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmssSSS");

    IdGenerator(){
        workerId = 0x000000FF & getLastIP();
    }
    public synchronized String nextId() {
        long timestamp = timeGen(); //获取当前毫秒数
        //如果服务器时间有问题(时钟后退) 报错。
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format(
                    "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        //如果上次生成时间和当前时间相同,在同一毫秒内
        if (lastTimestamp == timestamp) {
            //sequence自增,因为sequence只有12bit,所以和sequenceMask相与一下,去掉高位
            sequence = (sequence + 1) & sequenceMask;
            //判断是否溢出,也就是每毫秒内超过4095,当为4096时,与sequenceMask相与,sequence就等于0
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒
            }
        } else {
            sequence = 0L; //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加
        }
        lastTimestamp = timestamp;
        long suffix = (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
        //String datePrefix = DateFormatUtils.format(timestamp, "yyyyMMddHHmmssSSS");
        String datePrefix = FAST_DATE_FORMAT.format(timestamp);
        return datePrefix + suffix;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    private byte getLastIP(){
        byte lastip = 0;
        try{
            InetAddress ip = InetAddress.getLocalHost();
            byte[] ipByte = ip.getAddress();
            lastip = ipByte[ipByte.length - 1];
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return lastip;
    }
}

5.文件工具类

package cn.fx.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    /**
     * 文件的创建
     *
     * @param path
     * @return
     */
    public static boolean mkDirectory(String path) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                return file.mkdirs();
            } else {
                return false;
            }
        } catch (Exception e) {
        } finally {
            file = null;
        }
        return false;
    }

    /**
     * 先根遍历序递归删除文件夹
     *
     * @param dirFile 要被删除的文件或者目录
     * @return 删除成功返回true, 否则返回false
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在,则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }

    /**
     * 压缩文件
     */
    private static final int BUFFER_SIZE = 2 * 1024;
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            logger.debug("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("系统异常:", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("系统异常:", e);
                }
            }
        }
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) {
        byte[] buf = new byte[BUFFER_SIZE];
        try {
            if (sourceFile.isFile()) {
                // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
                zos.putNextEntry(new ZipEntry(name));
                // copy文件到zip输出流中
                int len;
                FileInputStream in = new FileInputStream(sourceFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                // Complete the entry
                zos.closeEntry();
                in.close();
            } else {
                File[] listFiles = sourceFile.listFiles();
                if (listFiles == null || listFiles.length == 0) {
                    // 需要保留原来的文件结构时,需要对空文件夹进行处理
                    if (KeepDirStructure) {
                        // 空文件夹的处理
                        zos.putNextEntry(new ZipEntry(name + "/"));
                        // 没有文件,不需要文件的copy
                        zos.closeEntry();
                    }
                } else {
                    for (File file : listFiles) {
                        // 判断是否需要保留原来的文件结构
                        if (KeepDirStructure) {
                            // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                            // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                            compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                        } else {
                            compress(file, zos, file.getName(), KeepDirStructure);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("系统异常:", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("系统异常:", e);
                }

            }
        }
    }

    /**
     * @param file     文件
     * @param filePath 文件存放路径
     * @param fileName 源文件名
     * @return
     */
    public static void upload(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 获取文件夹里的文件
     *
     * @param fileDir
     * @return
     */
    public static List<File> readFile(String fileDir) {
        List<File> fileList = new ArrayList<File>();
        File file = new File(fileDir);
        File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
        if (files == null) {// 如果目录为空,直接退出
            return null;
        }

        // 遍历,目录下的所有文件
        for (File f : files) {
            if (f.isFile()) {
                fileList.add(f);
            } else if (f.isDirectory()) {
                System.out.println(f.getAbsolutePath());
                readFile(f.getAbsolutePath());
            }
        }
        for (File f1 : fileList) {
            System.out.println(f1.getName());
        }
        return fileList;
    }
}

6.SftpUtil工具类

package cn.fx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SftpUtil {

    private static final String KEY = "StrictHostKeyChecking";

    private static final String VALUE = "no";

    private static final String TYPE = "sftp";


    public static ChannelSftp init(String host, Integer port, String username, String password) {
        ChannelSftp chnSftp = null;
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, port);
            session.setPassword(password);
            Properties config = new Properties();
            config.put(KEY, VALUE);
            session.setConfig(config);
            session.connect();
            Channel channel = session.openChannel(TYPE);
            channel.connect();
            chnSftp = (ChannelSftp) channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chnSftp;
    }

    @SuppressWarnings("rawtypes")
    public static List<String> getListInSftp(String host, Integer port, String userName, String password, String folderPath) {
        List<String> list = new LinkedList<String>();
        try {
            ChannelSftp chnSftp = init(host, port, userName, password);
            Vector vector = chnSftp.ls(folderPath);
            for (Object obj : vector) {
                String str = obj.toString();
                if (str.contains("-rw-r--r--")) {
                    str = str.substring(str.lastIndexOf(":") + 4);
                    list.add(str);
                }
            }
            chnSftp.getSession().disconnect();
            chnSftp.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    //下载
    public static void downloadFromSftp(String host, Integer port, String userName, String password, String folderPath, String imageName, String downloadFolderPath) {
        try {
            FileOutputStream fos = new FileOutputStream(downloadFolderPath + imageName);
            ChannelSftp chnSftp = init(host, port, userName, password);
            chnSftp.get(folderPath + imageName, fos);
            fos.close();
            chnSftp.getSession().disconnect();
            chnSftp.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //测试下载
    public static void main(String[] args) {
        downloadFromSftp("47.102.108.22", 19999, "fuxing", "fuxing1028", "/ReturnData/", "1.txt", "D:/123/");
    }

    /**
     * 上传文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     */
    public static boolean upload(String host, Integer port, String userName, String password, String directory, File uploadFile) {
        try {
            ChannelSftp sftp = init(host, port, userName, password);
            sftp.cd(directory);
            File file = new File(String.valueOf(uploadFile));
            FileInputStream fileInputStream = new FileInputStream(file);
            sftp.put(fileInputStream, file.getName());
            fileInputStream.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}

7.AES加密和解密

package cn.fx.util;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class TokenUtil {

    public static final String KEY = "fuxing19";

    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    public static String encode(String data) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            DESKeySpec dks = new DESKeySpec(KEY.getBytes());
            Key secretKey = keyFactory.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            return byte2hex(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            return null;
        }
    }

    public static String decode(String data) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            DESKeySpec dks = new DESKeySpec(KEY.getBytes());
            Key secretKey = keyFactory.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return new String(cipher.doFinal(hex2byte(data.getBytes())));
        } catch (Exception e) {
            return null;
        }
    }

    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException();
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值