1. 程式人生 > >Util工具類

Util工具類

public class Util {
    /**
     * log4j
     */
private final static Logger logger = LoggerFactory.getLogger(Util.class);
/**
     * 隨即獲取32位ID
     * <p>
* 2017年8月3日 13:26:45
     * xj
     *
     * @return String
     */
public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-"
, ""); } /** * 將指定資料轉換為int型 * * 2017年8月3日 13:28:34 * xj * * @param o 指定資料 * @return int */ public static int getInt(Object o) { if (o instanceof BigDecimal) { return ((BigDecimal) o).intValue(); } else if (o instanceof Integer) { return
((Integer) o).intValue(); } else if (o instanceof Float) { return ((Float) o).intValue(); } else if (o instanceof Double) { return ((Double) o).intValue(); } throw new RuntimeException("can't parse object to int"); } /** * 獲取股票得分表(SV_SCORE)當前月份表名 * *
@return */ public static String getCurrentScoreTableName() { String name = null; Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); // int month = calendar.get(Calendar.MONTH) + 1; // if (month < 10) { // name = "SV_SCORE_" + year + "0" + month; // } else { // name = "SV_SCORE_" + year + "" + month; // } name = "SV_SCORE_" + year; return name; } /** * 獲取股票得分表(SV_SCORE)指定格式的日期的月份表名 * <p> * 2017年8月8日 16:25:18 * xj * * @param date 指定日期 * @return String */ public static String getScoreTableNameByTime(String date) { String name = null; Calendar calendar = Calendar.getInstance(); calendar.setTime(Util.transformStringToDate(date, "yyyy-MM-dd")); int year = calendar.get(Calendar.YEAR); // int month = calendar.get(Calendar.MONTH) + 1; // if (month < 10) { // name = "SV_SCORE_" + year + "0" + month; // } else { // name = "SV_SCORE_" + year + "" + month; // } name = "SV_SCORE_" + year; return name; } /** * 獲取指定時間的最近半年時間月份第一天 * <p> * 2017年8月8日 17:19:10 * xj * * @param date 指定日期 * @return String[] */ public static String[] getHalfYear(Date date) { String[] last6Months = new String[6]; Calendar cal = Calendar.getInstance(); cal.setTime(date); //要先+1,才能把本月的算進去 cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); for (int i = 0; i < 6; i++) { //逐次往前推1個月 cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); last6Months[5 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-01"; } return last6Months; } /** * 獲取Date型別yyyy-MM-dd格式的當前時間 * * 2017年8月3日 10:56:09 * xj * * @return Date */ public static Date getCurrentDate() { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(date); Date curDay = null; try { curDay = format.parse(dateStr); } catch (ParseException e) { logger.error(e.getMessage(), e); } return curDay; } /** * 日期加減 * * @param date 指定日期 * @param dateFormat 指定日期格式 * @param year 加減年數 * @return -1 為日期格式錯誤 */ public static String minusYear(String date, String dateFormat, int year) { SimpleDateFormat format = new SimpleDateFormat(dateFormat); try { Calendar calendar = Calendar.getInstance(); Date now = format.parse(date); calendar.setTime(now); calendar.add(Calendar.YEAR, year); return format.format(calendar.getTime()); } catch (ParseException e) { logger.error(e.getMessage(), e); return "-1"; } } /** * 日期加減 * * @param date 指定日期 * @param dateFormat 指定日期格式 * @param day 加減天數 * @return -1 為日期格式錯誤 */ public static String minusDay(String date, String dateFormat, int day) { SimpleDateFormat format = new SimpleDateFormat(dateFormat); try { Calendar calendar = Calendar.getInstance(); Date now = format.parse(date); calendar.setTime(now); calendar.add(Calendar.DAY_OF_MONTH, day); return format.format(calendar.getTime()); } catch (ParseException e) { logger.error(e.getMessage(), e); return "-1"; } } /** * 日期加減 * * @param date 指定日期 * @param dateFormat 指定日期格式 * @param day 加減天數 * @return null 為日期格式錯誤 */ public static Date minusDate(String date, String dateFormat, int day) { SimpleDateFormat format = new SimpleDateFormat(dateFormat); try { Calendar calendar = Calendar.getInstance(); Date now = format.parse(date); calendar.setTime(now); calendar.add(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } catch (ParseException e) { logger.error(e.getMessage(), e); return null; } } /** * 將日期字串轉換為Date型別 * String型別的日期格式和要轉化的format格式必須一樣 * * @param dateStr 日期字串 * @param dateFormat 日期格式 yyyy-MM-dd * @return date */ public static Date transformStringToDate(String dateStr, String dateFormat) { Date date = null; DateFormat format = new SimpleDateFormat(dateFormat); try { date = format.parse(dateStr); } catch (ParseException e) { logger.error(e.getMessage(), e); } return date; } /** * 將Date型別轉換為日期字串 * * @param date 日期字串 * @param dateFormat 日期格式 * @return dateStr */ public static String transformDateToString(Date date, String dateFormat) { if (date == null || StringUtils.isEmpty(dateFormat)) { return ""; } DateFormat format = new SimpleDateFormat(dateFormat); return format.format(date); } /** * 獲取某日期區間的所有日期 日期倒序 * * @param startDate 開始日期 * @param endDate 結束日期 * @param dateFormat 日期格式 * @return 區間內所有日期 */ public static List<String> getPerDaysByStartAndEndDate(String startDate, String endDate, String dateFormat) { DateFormat format = new SimpleDateFormat(dateFormat); try { Date sDate = format.parse(startDate); Date eDate = format.parse(endDate); long start = sDate.getTime(); long end = eDate.getTime(); if (start > end) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(eDate); List<String> res = new ArrayList<String>(); while (end >= start) { res.add(format.format(calendar.getTime())); calendar.add(Calendar.DAY_OF_MONTH, -1); end = calendar.getTimeInMillis(); } return res; } catch (ParseException e) { logger.error(e.getMessage(), e); } return null; } /** * 獲取某日期區間的所有12月31日的日期 日期倒序 * * @param startDate 開始日期 yyyy-MM-dd * @param endDate 結束日期 yyyy-MM-dd * @return 區間內所有日期 */ public static List<String> getPerYearByStartAndEndDate(String startDate, String endDate) { String start = startDate.substring(0, startDate.indexOf("-")); String end = endDate.substring(0, endDate.indexOf("-")); int s = Integer.parseInt(start); int e = Integer.parseInt(end); if (!(end + "-12-31").equals(endDate)) { e--; } List<String> res = new ArrayList<String>(); while (e >= s) { res.add(e + "-12-31"); e--; } return res; } /** * 獲取某日期區間的年份 * * @param startDate 開始日期 yyyy * @param endDate 結束日期 yyyy * @return 區間內所有日期 */ public static List<String> getYearsByStartAndEndDate(String startDate, String endDate) { Integer s = Integer.parseInt(startDate); Integer e = Integer.parseInt(endDate); List<String> res = new ArrayList<String>(); while (e >= s) { res.add(e.toString()); e--; } return res; } /** * 對含有map的list排序 * * @param areaList 原始值 * @param isDesc TRUE:從大到小 FALSE:從小到大 */ public static void sortListMap(List<Map.Entry<String, Double>> areaList, final boolean isDesc) { Collections.sort(areaList, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { int flag = 1; if (isDesc) { if (o2.getValue() - o1.getValue() < 0) { flag = -1; } } else { if (o2.getValue() - o1.getValue() > 0) { flag = -1; } } return flag; } }); } /** * 對map中含有String型別的日期key值的list進行排序 * <p> * 2017年9月29日 17:19:09 * xj * * @param list List<Map<String,Object>>,String為日期 * @param format 日期格式 * @param isDesc TRUE:從大到小 FALSE:從小到大 */ public static void sortListStringDateMap(List list, final String format, final boolean isDesc) { Collections.sort(list, new Comparator() { @Override public int compare(Object o1, Object o2) { Map<String, Object> o1Map = (Map<String, Object>) o1; Map<String, Object> o2Map = (Map<String, Object>) o2; String o1Key = ""; for (String key : o1Map.keySet()) { o1Key = key; } String o2Key = ""; for (String key : o2Map.keySet()) { o2Key = key; } Integer o1K = Integer.valueOf(Util.transformDateToString(Util.transformStringToDate(o1Key, format), "yyyyMMdd")); Integer o2K = Integer.valueOf(Util.transformDateToString(Util.transformStringToDate(o2Key, format), "yyyyMMdd")); int flag = 1; if (isDesc) { if (o2K - o1K < 0) { flag = -1; } } else { if (o2K - o1K > 0) { flag = -1; } } return flag; } }); } /** * null轉為空字串 * * @param obj * @return */ public static Object nvl(Object obj) { if (null == obj) { return ""; } return obj; } /** * @methodName nullTrans * @describe 將空值轉化成空字串 * @author xj * @date 2017/10/18 15:49 * @param obj * @return java.lang.Object */ public static String nullTrans(Object obj){ String nullValue = "null"; String nuValue = "nu"; if (null == obj || nullValue.equals(obj) || nuValue.equals(obj)){ return ""; } return obj.toString(); } /** * 數字型別陣列轉換為以逗號分隔的字串 * * @param arr * @return */ public static String transformArrayToString(Object[] arr) { if (null == arr || arr.length == 0) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i]).append(","); } return sb.substring(0, sb.length() - 1); } /** * 字串型別陣列轉換為以逗號分隔的字串, 字串加引號 * * @param arr * @return */ public static String transformArrayToStringQ(Object[] arr) { if (null == arr || arr.length == 0) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append("'").append(arr[i]).append("'").append(","); } return sb.substring(0, sb.length() - 1); } /** * double型別加法,防止失去精度 * * @param d1 * @param d2 * @return */ public static double addDouble(Double d1, Double d2) { BigDecimal bd1 = new BigDecimal(d1.toString()); BigDecimal bd2 = new BigDecimal(d2.toString()); return bd1.add(bd2).doubleValue(); } /** * 比較兩個double是否相等 * * @param d1 * @param d2 * @return 當此 BigDecimal 在數字上小於、等於或大於 val 時,返回 -1、0 或 1。 */ public static int compareToDouble(String d1, String d2) { BigDecimal bd1 = new BigDecimal(d1); BigDecimal bd2 = new BigDecimal(d2); return bd1.compareTo(bd2); } /** * double型別減法,防止失去精度 * * @param d1 * @param d2 * @return */ public static Double subtractDouble(Double d1, Double d2) { BigDecimal bd1 = new BigDecimal(d1.toString()); BigDecimal bd2 = new BigDecimal(d2.toString()); return bd1.subtract(bd2).doubleValue(); } /** * double 乘法 * * @param d1 * @param d2 * @return */ public static Double multiplyDouble(Double d1, Double d2) { BigDecimal bd1 = new BigDecimal(d1.toString()); BigDecimal bd2 = new BigDecimal(d2.toString()); return bd1.multiply(bd2).doubleValue(); } /** * double 除法 * * @param d1 * @param d2 * @param scale 四捨五入 小數點位數 * @return */ public static Double divideDouble(Double d1, Double d2, int scale) { // 當然在此之前,你要判斷分母是否為0, // 為0你可以根據實際需求做相應的處理 BigDecimal bd1 = new BigDecimal(d1.toString()); BigDecimal bd2 = new BigDecimal(d2.toString()); return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 精度,四捨五入 * * @param d1 * @param scale * @return */ public static Double round(Double d1, int scale) { if (d1 == null) { return null; } BigDecimal bd1 = new BigDecimal(d1.toString()); return bd1.setScale(scale, RoundingMode.HALF_UP).doubleValue(); } /** * 轉碼以提供中文名檔案下載支援 * * @param fileName * @return */ public static String getAttachFileNameForCn(String fileName) { StringBuffer sb = new StringBuffer(); try { sb.append("filename=").append(URLEncoder.encode(fileName, "UTF-8")) .append(";filename*=UTF-8''").append(URLEncoder.encode(fileName, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } return sb.toString(); } /** * 判斷專案的架包目錄中是否存在upload資料夾、svUpload資料夾 * 如果存在直接返回svUpload資料夾完整url,如果不存在則建立upload資料夾、svUpload資料夾, * 在返回svUpload資料夾url * <p> * 2017年7月10日 15:16:19 * xj * * @return String */ public static String getUploadUrl() { String url = JarUrlUtil.getJarUrl(); url += File.separator + "upload"; File file2 = new File(url); if (!file2.isDirectory()) { file2.mkdir(); url += File.separator + "svUpload"; File file1 = new File(url); if (!file1.isDirectory()) { file1.mkdir(); } } else { url += File.separator + "svUpload"; File file1 = new File(url); if (!file1.isDirectory()) { file1.mkdir(); } } return url; } /** * 判斷專案的架包目錄中是否存在download資料夾, * 如果存在則返回download資料夾完成路徑,如果不存在,建立download資料夾,在返回其完整路徑。 * <p> * 2017年7月21日 10:32:54 * xj * * @return String */ public static String getDownloadUrl() { String url = JarUrlUtil.getJarUrl(); url += File.separator + "download"; File downloadFile = new File(url); if (!downloadFile.isDirectory()) { downloadFile.mkdir(); } return url; } /** * 判斷專案的架包目錄中是否存在template資料夾, * 如果存在則返回template資料夾完成路徑,如果不存在,建立template資料夾,在返回其完整路徑。 * <p> * 2017年7月27日 14:58:16 * xj * * @return String */ public static String getTemplateUrl() { String url = JarUrlUtil.getJarUrl(); url += File.separator + "template"; File templateFile = new File(url); if (!templateFile.isDirectory()) { templateFile.mkdir(); } return url; } /** * 判斷當前fileUrl是否存在fileName資料夾, * 如果存在則返回fileName資料夾完成路徑,如果不存在,建立fileName資料夾,在返回其完整路徑。 * <p> * 2017年7月28日 14:59:48 * xj * * @param fileUrl 檔案所在路徑 * @return String */ public static String getFileUrl(String fileUrl) { File file = new File(fileUrl); if (!file.isDirectory()) { file.mkdir(); } return fileUrl; } /** * 格式化數字 * * @param format * @param obj * @return */ public static String formatByDecimalFormat(String format, Object obj) {