ChineseToSpellUtils 中文拼写工具类
Capitalize 首字母大写
getCnASCII 将字符串转换成ASCII码
getFullSpell 获取汉字串拼音,英文字符不变 【首字母大写】
getPingYin 将字符串中的中文转化为拼音,其他字符不变
getFirstSpell 获取汉字串拼音首字母,英文字符不变
package com.yhl.ros.common.utils;
import java.util.Date;
import org.apache.commons.codec.digest.DigestUtils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* @date 2018年12月29日
* @description: 中文汉字转拼音
*/
public class ChineseToSpellUtils {
public static void main(String[] args) {
Long timestamp = new Date().getTime();
String appSecret = "554de0d59ebb5e32e3ac78c95366c142";
String str = "timestamp=" + timestamp + "&secret=" + appSecret;
String signNew = DigestUtils.md5Hex(str);
System.out.println("sign=" + signNew + ",timestamp=" + timestamp);
}
/**
* 获取汉字串拼音首字母,英文字符不变
*
* @param chinese
* 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
// 用StringBuffer(字符串缓冲)来接收处理的数据
StringBuffer sb = new StringBuffer();
// 字符串转换为字截数组
char[] arr = chinese.toCharArray();
// 创建转换对象
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 转换类型(大写or小写)
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 定义中文声调的输出格式
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
// 判断是否是汉子字符
if (arr[i] > 128) {
try {
// 提取汉字的首字母
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
if (temp != null) {
sb.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
// 如果不是汉字字符,直接拼接
sb.append(arr[i]);
}
}
return sb.toString().replaceAll("\\W", "").trim();
}
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputString
* @return 汉语拼音
*/
public static String getPingYin(String inputString) {
// 创建转换对象
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
// 转换类型(大写or小写)
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 定义中文声调的输出格式
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// 定义字符的输出格式
format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
// 转换为字节数组
char[] input = inputString.trim().toCharArray();
// 用StringBuffer(字符串缓冲)来接收处理的数据
StringBuffer output = new StringBuffer();
try {
for (int i = 0; i < input.length; i++) {
// 判断是否是一个汉子字符
if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output.append(temp[0]);
} else {
// 如果不是汉字字符,直接拼接
output.append(java.lang.Character.toString(input[i]));
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output.toString().toUpperCase();
}
/**
* 获取汉字串拼音,英文字符不变 【首字母大写】
*
* @param chinese
* 汉字串
* @return 汉语拼音
*/
public static String getFullSpell(String chinese) {
// 用StringBuffer(字符串缓冲)来接收处理的数据
StringBuffer sb = new StringBuffer();
// 字符串转换字节数组
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 转换类型(大写or小写)
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 定义中文声调的输出格式
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// 定义字符的输出格式
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
for (int i = 0; i < arr.length; i++) {
// 判断是否是汉子字符
if (arr[i] > 128) {
try {
sb.append(capitalize(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]));
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
// 如果不是汉字字符,直接拼接
sb.append(arr[i]);
}
}
return sb.toString();
}
/**
* 将字符串转换成ASCII码
*
* @param cnStr
* @return String
*/
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
// 将字符串转换成字节序列
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
// 将每个字符转换成ASCII码
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
/**
* 首字母大写
*
* @param str
* @return
*/
public static String capitalize(String str) {
char ch[];
ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
String newString = new String(ch);
return newString;
}
}
CollectionUtils 采集工具类
isEmpty 是否为空
isNotEmpty 是否不为空
getDiffSection 获取两个集合的差集
getInterSection 获取两个集合的交集
getUnionSection 获取两个集合的合集
splitList 分割List
isListEqual 判断两个集合是否相等
package com.yhl.ros.common.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* @ClassName: CollectionUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:06
*/
public class CollectionUtils<T> {
/**
* 初始化ArrayList
*
* @param elements
* @return
*/
@SafeVarargs
public static <T> List<T> createArrayList(T... elements) {
List<T> list = new ArrayList<T>();
for (T element : elements) {
list.add(element);
}
return list;
}
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
public static boolean isNotEmpty(Collection<?> collection) {
return (collection != null && !collection.isEmpty());
}
/**
* 获取两个集合的差集
*
* @param big
* 大集合
* @param small
* 小集合
* @return 两个集合的差集
*/
public static <T> Collection<T> getDiffSection(Collection<T> big, Collection<T> small) {
Set<T> differenceSet = Sets.difference(Sets.newHashSet(big), Sets.newHashSet(small));
return Lists.newArrayList(differenceSet);
}
public static <T> List<T> getDiffSection(Collection<T> big, T obj) {
Set<T> small = new HashSet<T>();
small.add(obj);
Set<T> differenceSet = Sets.difference(Sets.newHashSet(big), small);
return Lists.newArrayList(differenceSet);
}
/**
* 获取两个集合的交集
*
* @param c1
* @param c2
* @return
*/
public static <T> List<T> getInterSection(Collection<T> c1, Collection<T> c2) {
Set<T> intersections = Sets.intersection(Sets.newHashSet(c1), Sets.newHashSet(c2));
return Lists.newArrayList(intersections);
}
/**
* 获取两个集合的合集
*
* @param c1
* @param c2
* @return
*/
public static <T> List<T> getUnionSection(Collection<T> c1, Collection<T> c2) {
c1.addAll(c2);
Set<T> newHashSet = Sets.newHashSet(c1);
return Lists.newArrayList(newHashSet);
}
public static <T> List<List<T>> splitList(List<T> list, int pageSize) {
int listSize = list.size(); // list的大小
int page = (listSize + (pageSize - 1)) / pageSize; // 页数
List<List<T>> listArray = new ArrayList<List<T>>(); // 创建list数组 ,用来保存分割后的list
for (int i = 0; i < page; i++) { // 按照数组大小遍历
List<T> subList = new ArrayList<T>(); // 数组每一位放入一个分割后的list
for (int j = 0; j < listSize; j++) { // 遍历待分割的list
int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize; // 当前记录的页码(第几页)
if (pageIndex == (i + 1)) { // 当前记录的页码等于要放入的页码时
subList.add(list.get(j)); // 放入list中的元素到分割后的list(subList)
}
if ((j + 1) == ((j + 1) * pageSize)) { // 当放满一页时退出当前循环
break;
}
}
listArray.add(subList); // 将分割后的list放入对应的数组的位中
}
return listArray;
}
public static <T> boolean isListEqual(Collection<T> l0, Collection<T> l1) {
if (l0 == l1) {
return true;
}
if (l0 == null && l1 == null) {
return true;
}
if (l0 == null || l1 == null) {
return false;
}
if (l0.size() != l1.size()) {
return false;
}
for (Object o : l0) {
if (!l1.contains(o)) {
return false;
}
}
for (Object o : l1) {
if (!l0.contains(o)) {
return false;
}
}
return true;
}
}
CommonDateUtils 日期操作工具类
getYearByDate 根据日期获取年份
getMaxWeeksOfYear 获取年的最大周次(一年最多有多少周)
getDateByTime 根据时间(HH:mm)和日期 返回完整所需的日期时间
dateToString 根据Date和 日期格式(YYYY/MM/dd hh:mm:ss)
getDate 根据时间和天数,返回多少天后的时间
getCurrentTime 获取当前时间戳 20210120
package com.yhl.ros.common.utils;
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.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
/**
* @ClassName: CommonDateUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:06
*/
public class CommonDateUtils {
private CommonDateUtils() {
}
private static Map<String, String> weekDays = new HashMap<String, String>();
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String COMMON_DATE_STR1 = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy/MM/dd HH:mm:ss
*/
public static final String COMMON_DATE_STR2 = "yyyy/MM/dd HH:mm:ss";
/**
* yyyy-MM-dd
*/
public static final String COMMON_DATE_STR3 = "yyyy-MM-dd";
/**
* HH:mm
*/
public static final String COMMON_DATE_STR4 = "HH:mm";
static {
weekDays.put("0", "星期日");
weekDays.put("1", "星期一");
weekDays.put("2", "星期二");
weekDays.put("3", "星期三");
weekDays.put("4", "星期四");
weekDays.put("5", "星期五");
weekDays.put("6", "星期六");
}
public static int getYearByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 获取年的最大周次
*
* @param year
* @return 201709
*/
public static int getMaxWeeksOfYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
return calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
}
/**
* 根据时间(HH:mm)和日期 返回完整所需的日期时间
*
* @param date
* @param time
* 格式: HH:mm
* @return
*/
public static Date getDateByTime(Date date, String time) {
if (time == null || date == null)
return null;
Calendar calendar = Calendar.getInstance();
int departHour = Integer.parseInt(time.substring(0, time.length() - 3));
int departMin = Integer.parseInt(time.substring(time.length() - 2, time.length()));
calendar.setTime(date);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
departHour, departMin, 00);
return calendar.getTime();
}
/**
* 功能:通过日期和时间生成新的日期
*
* @param date
* 日期
* @param time
* 时间
* @param timeFormatStr
* 时间的格式字符串
* @return
*/
public static Date addDateTimeWithTimeStr(Date date, Date time, String timeFormatStr) {
String timeStr = dateToString(time, timeFormatStr);
return addDateTimeWithTimeStr(date, timeStr, timeFormatStr);
}
/**
* 功能:通过日期和时间生成新的日期
*
* @param date
* 日期
* @param time
* 时间
* @param timeFormatStr
* 时间的格式字符串
* @return
*/
public static Date addDateTimeWithTimeStr(Date date, String timeStr, String timeFormatStr) {
// yyyy-MM-dd + 空格 +时间字符串
String dateStr = dateToString(date, COMMON_DATE_STR3) + " " + timeStr;
return stringToDate(dateStr, COMMON_DATE_STR3 + timeFormatStr);
}
/**
* 根据开始时间和结束时间返回时间段内的时间集合
*
* @param beginDate
* @param endDate
* @return List
*/
public static List<Date> getDatesBetweenTwoDate(Date beginDate, Date endDate) {
List<Date> lDate = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
while (endDate.after(cal.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
lDate.add(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
}
if (null != dateToString(beginDate) && !dateToString(beginDate).equals(dateToString(endDate))) {
lDate.add(endDate);// 把结束时间加入集合
}
return lDate;
}
/**
* 根据数字转换成对应的星期
*/
public static String getWeekDaysCn(String str) {
String week = "";
char[] chars = str.toCharArray();
for (char c : chars) {
if ("0".equals(String.valueOf(c))) {
week += "日";
}
if ("1".equals(String.valueOf(c))) {
week += "一";
}
if ("2".equals(String.valueOf(c))) {
week += "二";
}
if ("3".equals(String.valueOf(c))) {
week += "三";
}
if ("4".equals(String.valueOf(c))) {
week += "四";
}
if ("5".equals(String.valueOf(c))) {
week += "五";
}
if ("6".equals(String.valueOf(c))) {
week += "六";
}
}
return week;
}
/**
* 根据当前日期获取N天后的日期
*
* @return
*/
public static Date getDateByTaDay(Date date, int number) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, number);
Date nextDay = calendar.getTime();
return nextDay;
}
public static String min2HHmmss(long mins) {
String hhmmss = "";
if (mins <= 0) {
hhmmss = "00:00:00";
return hhmmss;
}
long hour = mins / 60;
long min = mins - hour * 60;
String hourStr = String.valueOf(hour);
String minStr = String.valueOf(min);
if (hour < 10)
hourStr = "0" + hourStr;
if (min < 10)
minStr = "0" + minStr;
hhmmss = hourStr + ":" + minStr + ":00";
return hhmmss;
}
/**
* 参数格式 HH:mm
*
* @param mins
* @return
*/
public static Integer hhmm2Min(String mins) {
String[] minStr = mins.split(":");
return Integer.parseInt(minStr[0]) * 60 + Integer.parseInt(minStr[1]);
}
/**
* 获取日期所在周次 201709/201749
*
* @param date
* @return
*/
public static int getWeeksWithYearByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int weeks = getWeeksByDate(date);
String weekStr = "";
if (weeks < 10) {
weekStr = "0" + weeks;
} else {
weekStr = String.valueOf(weeks);
}
return Integer.valueOf(year + weekStr);
}
/**
* 获取日期所在周次 9、32
*
* @param date
* @return
*/
public static int getWeeksByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.setTime(date);
int weeks = calendar.get(Calendar.WEEK_OF_YEAR);
return weeks;
}
/**
* 功能:获取日期对应的星期中文名
*
* @param date
* @return
*/
public static String getWeekDayCnOfDate(Date date) {
return weekDays.get(getWeekDayOfDate(date));
}
/**
* 取得给定时间对应的星期
*
* @return
*/
public static String getWeekDayOfDate(Date date) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
return "" + (c.get(Calendar.DAY_OF_WEEK) - 1);
}
/**
* 获取某周的第一天
*
* @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.setFirstDayOfWeek(Calendar.MONDAY);
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());
}
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();
}
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 date
* @return
*/
public static int getDayOfWeek(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
int result = instance.get(Calendar.DAY_OF_WEEK) - 1;
return result == 0 ? 7 : result;
}
/**
* 获取月号
*
* @param date
* @return
*/
public static int getDayOfMonth(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
return instance.get(Calendar.DAY_OF_MONTH);
}
/**
* 求两个日期差
*
* @param beginDate
* 开始日期
* @param endDate
* 结束日期
* @return 两个日期相差天数
*/
public static Long getDateInterval(Date startDate, Date endDate) {
if (startDate == null || endDate == null) {
return null;
}
if (startDate.after(endDate)) {
return -1L;
}
long interval = endDate.getTime() - startDate.getTime();
return interval / (1000 * 60 * 60 * 24);
}
/**
* 计算两个日期之间相隔的数量,如天数,月数。。。具体由field决定
*
* @param after
* @param before
* @param field
* 参考Calendar.YEAR...
* @return
*/
public static int getDateInterval(Date after, Date before, int field) {
if (after == null || before == null) {
return 0;
}
Calendar calAfter = Calendar.getInstance();
calAfter.setTime(after);
Calendar calBefore = Calendar.getInstance();
calBefore.setTime(before);
return calAfter.get(field) - calBefore.get(field);
}
/**
* 功能:求两个日期相差小时数
*
* @param startDate
* @param endDate
* @return
*/
public static Long getHourInterval(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
return -1L;
}
long interval = endDate.getTime() - startDate.getTime();
return interval / (1000 * 60 * 60);
}
/**
* 求两个日期差(分钟)
*
* @param beginDate
* 开始日期
* @param endDate
* 结束日期
* @return 两个日期相差分钟
*/
public static Long getMinuteInterval(Date startDate, Date endDate) {
long interval = endDate.getTime() - startDate.getTime();
return interval / (1000 * 60);
}
/**
* 功能:获取不带时分秒的时间
*
* @param sourceDate
* @return
*/
public static Date getShortDate(Date sourceDate) {
if (sourceDate == null) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(COMMON_DATE_STR3);
String strDate = dateFormat.format(sourceDate);
try {
return dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 功能:返回当前月份第一天
*
* @return
*/
public static Date getCurrentMonthFristDay() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* 功能:返回当前月份最后一天
*
* @return
*/
public static Date getCurrentMonthLastDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
/**
* 功能:返回当前月份最后一天
*
* @return
*/
public static Date getNextMonthLastDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
/**
* 获取日期所在周的七天(周一开始)
*
* @return
*/
public static String[] getWeekDatesStr(Date date) {
HashMap<String, Date> dateMap = getWeekDates(date);
List<Date> dateList = new ArrayList<Date>(dateMap.values());
String[] datesStr = new String[dateList.size()];
for (int i = 0; i < dateList.size(); i++) {
datesStr[i] = dateToString(dateList.get(i), COMMON_DATE_STR3);
}
return datesStr;
}
/**
* 功能:返回参数所在星期的7天, 如,传入日期'2011-06-02'(星期四), 则返回20011-06-02所在星期的周日至周一的日期Map:
* {(SUN:'2011-05-29'),(MON:'2011-05-30'),(TUE:'2011-05-31'),(WED:'2011-06-01'),(THU:'2011-06-02'),(FRI:'2011-06-03',(SAT:'2011-06-04')}
*
* @param date
* @return
*/
public static HashMap<String, Date> getWeekDates(Date date) {
HashMap<String, Date> dates = new HashMap<String, Date>();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setFirstDayOfWeek(Calendar.MONDAY);
int index = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK, (-1) * (index - 1));
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("MON", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("TUE", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("WED", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("THU", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("FRI", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("SAT", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("SUN", c.getTime());
return dates;
}
// 计算当月有多少天
public static int days(int year, int month) {
int days = 0;
if (month != 2) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
}
} else {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days = 29;
else
days = 28;
}
return days;
}
/**
* 功能: 取传入参数日期的当月第一天
*
* @param date
* @return
*/
public static Date getMonthFirstDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 功能: 取传入参数日期的当月最后一天
*
* @param date
* @return
*/
public static Date getMonthLastDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.add(Calendar.DAY_OF_YEAR, -1);
return cal.getTime();
}
/**
* 功能: 平移月份
*
* @param date
* @param monthNum
* @return
*/
public static Date moveDate(Date date, int monthNum) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, monthNum);
return cal.getTime();
}
/**
* 功能: 根据days参数移动日期,days可为正 可为负 日期去除时分秒
*
* @param date
* @param days
* @return
*/
public static Date moveDay(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, days);
return cal.getTime();
}
/**
* 获取当前日期,不带时分秒
*
* @return
*/
public static Date getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
return parseString(sdf.format(new Date()));
}
public static Date parseString(String strDate) {
if (StringUtils.isNotBlank(strDate)) {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
try {
return sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static Date parseString(String strDate, String format) {
if (StringUtils.isNotBlank(strDate)) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 分钟转小时
*
* @param min
* @return
*/
public static String minToHour(int min) {
if (min == 0)
return "0";
int hour = min / 60;
int leftMin = min % 60;
String minStr = leftMin < 10 ? "0" + leftMin : leftMin + "";
return hour + ":" + minStr;
}
/**
* 功能: 判断两个日期的间隔天数是否超过参数值 超过返回true 未超过返回false
*
* @param beforeDate
* 前一日期
* @param lastDate
* 后一日期
* @param days
* 间隔天数
* @return
*/
public static Boolean checkDistanceDay(Date beforeDate, Date lastDate, int days) {
long interval = 0l;
if (beforeDate.before(lastDate)) {
interval = lastDate.getTime() - beforeDate.getTime();
} else {
interval = beforeDate.getTime() - lastDate.getTime();
}
int betweenDays = (int) (interval / (1000 * 60 * 60 * 24));
if (betweenDays > days) {
return true;
} else if (betweenDays == 0 && days == 0) {
return true;
} else {
return false;
}
}
/**
* 功能:平移小时
*
* @param date
* @param hour
* @return
*/
public static Date moveHour(Date date, int hour) {
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hour);
return cal.getTime();
}
/**
* 功能:平移分钟
*
* @param date
* @param minute
* @return
*/
public static Date moveMinute(Date date, int minute) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, minute);
return cal.getTime();
}
/**
* 功能:获取Date中某个属性的值
*
* @param date
* @param field
* java.util.Calendar类中定义
* @return
*/
public static int getDateField(Date date, int field) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(field);
}
/**
* 功能: 根据参数years平移年份
*
* @param date
* @param years
* @return
*/
public static Date moveYear(Date date, int years) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, years);
return cal.getTime();
}
/**
* 功能:根据年份获得这年的最后一天
*
* @param year
* @return
*/
public static Date getLastDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, 11, 31);
return cal.getTime();
}
/**
* 功能:根据年份获得这年的第一天
*
* @param year
* @return
*/
public static Date getFirstDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, 0, 1);
return cal.getTime();
}
/**
* 功能:返回指定年度指定季度的第一天
*
* @param quarter,{1,2,3,4}
* @param year
* @return
*/
public static Date qetQuarterFirstDay(int quarter, int year) {
String firstDateStr = null;
Date firstDate = null;
if (year > 0) {
if (quarter >= 1 && quarter <= 4) {
switch (quarter) {
case 1: {
firstDateStr = year + "-01-01";
break;
}
case 2: {
firstDateStr = year + "-04-01";
break;
}
case 3: {
firstDateStr = year + "-07-01";
break;
}
case 4: {
firstDateStr = year + "-10-01";
break;
}
default:
;
}
}
}
if (firstDateStr != null) {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
try {
firstDate = sdf.parse(firstDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
return firstDate;
}
/**
* 功能:返回指定年度指定季度的最后一天
*
* @param quarter
* @param year
* @return
*/
public static Date getQuarterLastDay(int quarter, int year) {
Date quarterFirstDay = qetQuarterFirstDay(quarter, year);
if (quarterFirstDay != null) {
return getQuarterLastDay(quarterFirstDay);
} else
return null;
}
/**
* 功能:返回参数日期所在季度第一天
*
* @param date
* @return
*/
public static Date getQuarterFirstDay(Date date) {
int year = getDateField(date, Calendar.YEAR);
int quarter = getQuarter(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
switch (quarter) {
case 1: {
c.set(Calendar.MONTH, 0);
break;
}
case 2: {
c.set(Calendar.MONTH, 3);
break;
}
case 3: {
c.set(Calendar.MONTH, 6);
break;
}
case 4: {
c.set(Calendar.MONTH, 9);
break;
}
default:
;
}
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* 功能:返回参数日期所在季度最后一天
*
* @param date
* @return
*/
public static Date getQuarterLastDay(Date date) {
int year = getDateField(date, Calendar.YEAR);
int quarter = getQuarter(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
switch (quarter) {
case 1: {
c.set(Calendar.MONTH, 3);
break;
}
case 2: {
c.set(Calendar.MONTH, 6);
break;
}
case 3: {
c.set(Calendar.MONTH, 9);
break;
}
case 4: {
c.set(Calendar.YEAR, year + 1);
c.set(Calendar.MONTH, 0);
break;
}
default:
;
}
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DAY_OF_YEAR, -1);
return c.getTime();
}
/**
* 功能:返回参数日期所在季度, 1:第一季度 2:第二季度 3:第三季度 4:第四季度
*
* @param date
* @return
*/
public static int getQuarter(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
switch (month) {
case 0:
return 1;
case 1:
return 1;
case 2:
return 1;
case 3:
return 2;
case 4:
return 2;
case 5:
return 2;
case 6:
return 3;
case 7:
return 3;
case 8:
return 3;
case 9:
return 4;
case 10:
return 4;
case 11:
return 4;
default:
;
}
return -1;
}
/**
* @description:String转换为Date pattern
* @param stringDate
* @return
* @throws ParseException
*/
public static Date stringToDate(String stringDate, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = null;
try {
date = sdf.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* @description:String转换为Date yyyy-MM-dd
* @param stringDate
* @return
* @throws ParseException
*/
public static Date stringToDate(String stringDate) {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
Date date = null;
try {
date = sdf.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* @description:String转换为Date yyyy-MM-dd
* @param stringDate
* @return
* @throws ParseException
*/
public static String dateToString(Date formatDate) {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
if (null == formatDate)
return null;
String date = sdf.format(formatDate);
return date;
}
/**
* @description:String转换为Date yyyy-MM
* @param stringDate
* @return
* @throws ParseException
*/
public static String dateToString2(Date formatDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
if (null == formatDate)
return null;
String date = sdf.format(formatDate);
return date;
}
/**
* @description:date转换为String yyyy年MM月dd日 hh:mm:ss
* @param stringDate
* @return
* @throws ParseException
*/
public static String dateToString3(Date Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
String dateString = null;
try {
dateString = sdf.format(Date);
} catch (Exception e) {
e.printStackTrace();
}
return dateString;
}
/**
* @description:date转换为String yyyy/MM/dd/ hh:mm:ss
* @param Date
* @return
* @throws ParseException
*/
public static String dateToString5(Date Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateString = null;
try {
dateString = sdf.format(Date);
} catch (Exception e) {
e.printStackTrace();
}
return dateString;
}
public static String dateToString4(Date Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String dateString = null;
try {
dateString = sdf.format(Date);
} catch (Exception e) {
e.printStackTrace();
}
return dateString;
}
/**
* 格式化日期
*
* @param Date
* @param pattern
* @return
*/
public static Date formatDate(Date Date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String dateString = null;
Date date = null;
try {
dateString = sdf.format(Date);
date = stringToDate(dateString, pattern);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/**
* 获取一天的起始时间
*
* @param date
*/
public static Date getDayFirstTime(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);
return cal.getTime();
}
/**
* 获取一天的结束时间
*
* @param date
* @return
*/
public static Date getDayLastTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
/**
* 获取一天的起始时间
*
* @param date
*/
public static Date getDayFirstTimeForTimingSheet(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 获取一天的结束时间
*
* @param date
* @return
*/
public static Date getDayLastTimeForTimingSheet(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date stringToDates(String str) throws Exception {
DateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss 'UTC'Z yyyy", Locale.ENGLISH);
Date date = df.parse(str);
return date;
}
/**
* 获取当前时间戳
*
* @return
*/
public static String getCurrentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date);
return str;
}
public static String dateToString(Date date, String pattern) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String result = sdf.format(date);
return result;
}
return "";
}
public static Date getDate(Date date, int intervalDay) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_YEAR, intervalDay);
return c.getTime();
}
public static Date getIntervalMonthLastDay(Date date, int intervalMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, intervalMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
public static Date getIntervalMonthMinDay(Date date, int intervalMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, intervalMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 15);
return c.getTime();
}
/**
*
* @param smdate
* @param bdate
* @return
* @throws ParseException
*/
public static int daysBetween(Date startDate, Date endDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
startDate = sdf.parse(sdf.format(startDate));
endDate = sdf.parse(sdf.format(endDate));
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
long time1 = cal.getTimeInMillis();
cal.setTime(endDate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
System.out.println(between_days);
return Integer.parseInt(String.valueOf(between_days)) + 1;
}
/**
* 判断是否为同一天
*
* @param day1
* @param day2
* @return
*/
public static boolean isSameDay(Date day1, Date day2) {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
String ds1 = sdf.format(day1);
String ds2 = sdf.format(day2);
if (ds1.equals(ds2)) {
return true;
} else {
return false;
}
}
/**
* 字符串的日期格式的计算
*/
public static int daysBetween(String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE_STR3);
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days)) + 1;
}
/**
* 把分钟转换为小时显示,格式如:2:50表示2小时50分钟
*
* @param mins
* @return
*/
public static String formatMinutes2Hours(Long mins) {
if (mins == null || mins.longValue() == 0)
return "0";
return (mins / 60 < 10 ? "0" + mins / 60 : mins / 60) + ":" + StringUtils.leftPad("" + mins % 60, 2, "0");
}
/**
* 把分钟转换为小时显示,格式如:2小时50分钟
*
* @param mins
* @return
*/
public static String formatMinutes2HoursCN(Long mins) {
if (mins == null || mins.longValue() == 0)
return "0";
return (mins / 60 < 10 ? "0" + mins / 60 : mins / 60) + "小时" + StringUtils.leftPad("" + mins % 60, 2, "0")
+ "分钟";
}
/**
* 删除给定Date的时分秒毫秒
*
* @param now
* @return
*/
public static Date truncateTimeOfDate(java.util.Date now) {
if (now == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
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();
}
/**
* 给定的日期加上addTime的时间
*
* @param now
* @param addTime
* 毫秒
* @return
*/
public static java.util.Date addDate(java.util.Date now, long addTime) {
if (now == null) {
return null;
}
return new java.util.Date(now.getTime() + addTime);
}
public static java.util.Date addDate(java.util.Date now, int year, int month, int day, int hour, int minute,
int second, int millSecond) {
if (now == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.YEAR, year);
c.add(Calendar.MONTH, month);
c.add(Calendar.DATE, day);
c.add(Calendar.HOUR_OF_DAY, hour);
c.add(Calendar.MINUTE, minute);
c.add(Calendar.SECOND, second);
c.add(Calendar.MILLISECOND, millSecond);
return c.getTime();
}
public static java.util.Date addDate(java.util.Date now, int year, int month, int day, int hour, int minute,
int second) {
return addDate(now, year, month, day, hour, minute, second, 0);
}
public static java.util.Date addDate(java.util.Date now, int hour, int minute, int second) {
return addDate(now, 0, 0, 0, hour, minute, second, 0);
}
public static java.util.Date addDateField(java.util.Date now, int field, int amount) {
if (now == null) {
return null;
}
if (amount == 0) {
return now;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(field, amount);
return c.getTime();
}
/**
* 功能:获取两个日期之间的所有日期
*
* @param startDate
* 开始日期
* @param endDate
* 结束日期
* @return
*/
public static List<Date> getIntervalDates(Date startDate, Date endDate) {
List<Date> result = new ArrayList<Date>();
Long intervalDay = getDateInterval(CommonDateUtils.truncateTimeOfDate(startDate),
CommonDateUtils.truncateTimeOfDate(endDate));
if (intervalDay < 0)
return result;
for (Long i = 0L; i <= intervalDay; i++) {
Date currentDate = addDateField(startDate, Calendar.DATE, i.intValue());
result.add(currentDate);
}
return result;
}
/**
* 判断一个字符串是不是一个合法的日期格式
*
* @param str
* 需要判断的字符串
* @param pattern
* 合法日期格式
* @return
*/
public static boolean isValidDate(String str, String pattern) {
boolean convertSuccess = true;
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}
/**
*
* @param nowDate
* 要比较的时间
* @param startDate
* 开始时间
* @param endDate
* 结束时间
* @return true在时间段内,false不在时间段内
* @throws Exception
*/
public static boolean hourMinuteBetween(String nowDate, String startDate, String endDate) throws Exception {
if (StringUtils.isBlank(nowDate) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
return false;
}
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date now = format.parse(nowDate);
Date start = format.parse(startDate);
Date end = format.parse(endDate);
long nowTime = now.getTime();
long startTime = start.getTime();
long endTime = end.getTime();
return nowTime >= startTime && nowTime <= endTime;
}
/**
* 判断时间段2是否与时间段1有重叠
*
* @param startDate1
* @param endDate1
* @param startDate2
* @param endDate2
* @return
*/
public static boolean isContain(Date startDate1, Date endDate1, Date startDate2, Date endDate2) {
if (startDate2.compareTo(startDate1) >= 0 && startDate2.compareTo(endDate1) <= 0)
return true;
if (endDate2.compareTo(endDate1) <= 0 && endDate2.compareTo(startDate1) >= 0)
return true;
if (startDate2.compareTo(startDate1) <= 0 && endDate2.compareTo(endDate1) >= 0)
return true;
return false;
}
/**
* 分钟转小时分钟 (用做展示使用) 若分钟为0 则不显示
*
* @param min
* @return 10h55m 或 10h
*/
public static String minToHourMin(int min) {
if (min == 0)
return "0";
int hour = min / 60;
int leftMin = min % 60;
if (leftMin == 0) {
return hour + "h";
} else {
String minStr = leftMin < 10 ? "0" + leftMin : leftMin + "";
if (hour == 0) {
return minStr + "m";
} else {
return hour + "h" + minStr + "m";
}
}
}
}
CoordinateUtils 距离操作工具类
metreDistance 返回double 类型的距离,向上进行四舍五入,距离精确到厘米,单位为米
kilometreDistance 返回double 类型的距离,向上进行四舍五入,距离精确到米,单位为公里
checkCoordinate 验证经纬度格式是否正确
package com.yhl.ros.common.utils;
import java.math.BigDecimal;
import java.util.regex.Pattern;
import com.yhl.ros.common.CoordinatePoint;
import com.yhl.ros.common.Point;
/**
* @ClassName: CoordinateUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:07
*/
public class CoordinateUtils {
private static final String LON_MATCH = "[\\-+]?(0?\\d{1,2}|0?\\d{1,2}\\.\\d{1,7}|1[0-7]?\\d|1[0-7]?\\d\\.\\d{1,7}|180|180\\.0{1,7})";
private static final String LAT_MATCH = "[\\-+]?([0-8]?\\d|[0-8]?\\d\\.\\d{1,7}|90|90\\.0{1,7})";
private static final double EARTH_RADIUS = 637_1393.00D;
private static final double RADIAN = Math.PI / 180.00D;
private static final double HALF = 0.5D;
/**
* @param point1 坐标点1
* @param point2 坐标点2
* @return 返回double 类型的距离,向上进行四舍五入,距离精确到厘米,单位为米
*/
public static double metreDistance(Point point1, Point point2) {
double lat1 = point1.x();
double lon1 = point1.y();
double lat2 = point2.x();
double lon2 = point2.y();
double x, y, a, b, distance;
lat1 *= RADIAN;
lat2 *= RADIAN;
x = lat1 - lat2;
y = lon1 - lon2;
y *= RADIAN;
a = Math.sin(x * HALF);
b = Math.sin(y * HALF);
distance = EARTH_RADIUS * Math.asin(Math.sqrt(a * a + Math.cos(lat1) * Math.cos(lat2) * b * b)) / HALF;
return new BigDecimal(distance).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* @param point1 坐标点1
* @param point2 坐标点2
* @return 返回double 类型的距离,向上进行四舍五入,距离精确到米,单位为公里
*/
public static double kilometreDistance(Point point1, Point point2) {
double lat1 = point1.x();
double lon1 = point1.y();
double lat2 = point2.x();
double lon2 = point2.y();
double x, y, a, b, distance;
lat1 *= RADIAN;
lat2 *= RADIAN;
x = lat1 - lat2;
y = lon1 - lon2;
y *= RADIAN;
a = Math.sin(x * HALF);
b = Math.sin(y * HALF);
distance = EARTH_RADIUS * Math.asin(Math.sqrt(a * a + Math.cos(lat1) * Math.cos(lat2) * b * b)) / HALF / 1000;
return new BigDecimal(distance).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static boolean checkCoordinate(String longitude, String latitude) {
boolean longitudeFlag = false;
boolean latitudeFlag = false;
try {
if (Pattern.matches(LAT_MATCH, latitude)) {
latitudeFlag = true;
}
if (Pattern.matches(LON_MATCH, longitude)) {
longitudeFlag = true;
}
Double.parseDouble(longitude);
Double.parseDouble(latitude);
if (longitudeFlag && latitudeFlag) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
public static void main(String[] args) {
// Point point1 = new CoordinatePoint(39.941037, 116.434027);
// Point point2 = new CoordinatePoint(39.941564, 116.461665);
// System.out.println(kilometreDistance(point1, point2));
System.out.println(checkCoordinate( "116.434027","39.941037"));
}
}
CronUtils 定时器工具类
- buildAnalysisCronExpression 生成cron表达式 参数:小时 分钟 周
package com.yhl.ros.common.utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.cronutils.builder.CronBuilder;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.field.expression.FieldExpression;
import com.cronutils.model.field.expression.FieldExpressionFactory;
import com.cronutils.model.field.expression.On;
/**
*
* @ClassName: CronUtils
* @Package: com.yhl.ros.common.utils
* @Description: cron表达式工具类
* @Date: 2020-04-15 16:34
*/
public class CronUtils {
private static CronBuilder cronBuilder;
static {
cronBuilder = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
}
public static String buildAnalysisCronExpression(Integer hour, Integer minute,String week) {
if(StringUtils.isNotEmpty(week)) {
String[] split = week.split(",");
if (split.length > 0) {
List<FieldExpression> flist = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
On on = FieldExpressionFactory.on(Integer.parseInt(split[i]));
flist.add(on);
}
Cron cron = cronBuilder.withDoW(FieldExpressionFactory.and(flist)).withYear(FieldExpressionFactory.always())
.withDoM(FieldExpressionFactory.questionMark()).withMonth(FieldExpressionFactory.always())
.withHour(FieldExpressionFactory.on(hour)).withMinute(FieldExpressionFactory.on(minute))
.withSecond(FieldExpressionFactory.on(0)).instance();
return cron.asString();
}
}
Cron cron = cronBuilder.withDoW(FieldExpression.questionMark()).withYear(FieldExpressionFactory.always())
.withDoM(FieldExpressionFactory.always()).withMonth(FieldExpressionFactory.always())
.withHour(FieldExpressionFactory.on(hour)).withMinute(FieldExpressionFactory.on(minute))
.withSecond(FieldExpressionFactory.on(0)).instance();
return cron.asString();
}
public static void main(String[] args) {
System.out.println(buildAnalysisCronExpression(12, 30,""));
System.out.println(buildAnalysisCronExpression(12, 30,"1,2"));
}
}
CSVUtils CSV操作工具类
exportByList 创建表
package com.yhl.ros.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
/**
* @ClassName: CSVUtils
* @Package: com.yhl.ros.common.utils
* @Description: CSV操作工具类
* @Date: 2020-02-12 01:07
*/
public class CSVUtils {
public static void exportByList(String[] headers, List<List<String>> dataList) throws FileNotFoundException {
FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
exportByList(headers, dataList, fileos);
}
public static void exportByList(String[] headers, List<List<String>> dataList, OutputStream os) {
OutputStreamWriter osw = null;
CSVFormat csvFormat = null;
CSVPrinter csvPrinter = null;
try {
osw = new OutputStreamWriter(os, "GBK");// 如果是UTF-8时,WPS打开是正常显示,而微软的excel打开是乱码,
csvFormat = CSVFormat.DEFAULT.withHeader(headers);
csvPrinter = new CSVPrinter(osw, csvFormat);
for (int i = 0; i < dataList.size(); i++) {
List<String> values = dataList.get(i);
csvPrinter.printRecord(values);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(os, csvPrinter);
}
}
public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList)
throws FileNotFoundException {
FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
exportByLinked(headers, dataList, fileos);
}
public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList, OutputStream os) {
OutputStreamWriter osw = null;
CSVFormat csvFormat = null;
CSVPrinter csvPrinter = null;
try {
osw = new OutputStreamWriter(os, "GBK");
csvFormat = CSVFormat.DEFAULT.withHeader(headers);
csvPrinter = new CSVPrinter(osw, csvFormat);
for (int i = 0; i < dataList.size(); i++) {
List<String> values = new ArrayList<String>();
LinkedHashMap<String, Object> rowHashMap = dataList.get(i);
Set<String> keys = rowHashMap.keySet();
for (String key : keys) {
values.add(String.valueOf(rowHashMap.get(key)));
}
csvPrinter.printRecord(values);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(os, csvPrinter);
}
}
private static void close(OutputStream os, CSVPrinter csvPrinter) {
if (csvPrinter != null) {
try {
csvPrinter.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
csvPrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CusAccessObjectUtil Cus访问对象工具类
获取对象的IP地址等信息
package com.yhl.ros.common.utils;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义访问对象工具类
*
* 获取对象的IP地址等信息
*
* @author X-rapido
*
*/
public class CusAccessObjectUtil {
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
*
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
*
* 用户真实IP为: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
DateUtils 日期工具类
package com.yhl.ros.common.utils;
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.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* @ClassName: DateUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:09
*/
public class DateUtils {
/**
* 时间戳处理
*/
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
/**
* @date 14:25 2018/11/16 根据时间获取序号
*/
public static int getIndex(Date date) {
return Integer.parseInt(simpleDateFormat.format(date).split(":")[0]);
}
private static Map<String, String> weekDays = new HashMap<String, String>();
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String COMMON_DATE_STR1 = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy/MM/dd HH:mm:ss
*/
public static final String COMMON_DATE_STR2 = "yyyy/MM/dd HH:mm:ss";
/**
* yyyy-MM-dd
*/
public static final String COMMON_DATE_STR3 = "yyyy-MM-dd";
/**
* HH:mm
*/
public static final String COMMON_DATE_STR4 = "HH:mm";
/**
* yyyyMMddHHmm
*/
public static final String COMMON_DATE_STR5 = "yyyyMMddHHmm";
static {
weekDays.put("0", "星期日");
weekDays.put("1", "星期一");
weekDays.put("2", "星期二");
weekDays.put("3", "星期三");
weekDays.put("4", "星期四");
weekDays.put("5", "星期五");
weekDays.put("6", "星期六");
}
public static int getYearByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 获取年的最大周次
*
* @param year
* @return 201709
*/
public static int getMaxWeeksOfYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
return calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
}
public static Date getBeginYearMonthDateTime(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
String dateTime = dateToString(c.getTime()) + " 00:00:00";
return stringToDate(dateTime, "yyyy-MM-dd HH:mm:ss");
}
public static Date getEndYearMonthDateTime(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DATE, 1);
c.roll(Calendar.DATE, -1);
String dateTime = dateToString(c.getTime()) + " 23:59:59";
return stringToDate(dateTime, "yyyy-MM-dd HH:mm:ss");
}
/**
* 根据时间(HH:mm)和日期 返回完整所需的日期时间
*
* @param date
* @param time
* 格式: HH:mm
* @return
*/
public static Date getDateByTime(Date date, String time) {
if (time == null || date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
int departHour = Integer.parseInt(time.substring(0, time.length() - 3));
int departMin = Integer.parseInt(time.substring(time.length() - 2, time.length()));
calendar.setTime(date);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
departHour, departMin, 00);
return calendar.getTime();
}
/**
* 功能:通过日期和时间生成新的日期
*
* @param date
* 日期
* @param time
* 时间
* @param timeFormatStr
* 时间的格式字符串
* @return
*/
public static Date addDateTimeWithTimeStr(Date date, Date time, String timeFormatStr) {
String timeStr = dateToString(time, timeFormatStr);
return addDateTimeWithTimeStr(date, timeStr, timeFormatStr);
}
/**
* 功能:通过日期和时间生成新的日期
*
* @param date
* 日期
* @param time
* 时间
* @param timeFormatStr
* 时间的格式字符串
* @return
*/
public static Date addDateTimeWithTimeStr(Date date, String timeStr, String timeFormatStr) {
// yyyy-MM-dd + 空格 +时间字符串
String dateStr = dateToString(date, "yyyy-MM-dd") + " " + timeStr;
return stringToDate(dateStr, "yyyy-MM-dd " + timeFormatStr);
}
public static Date getZeroHourMinute() {
TimeZone default1 = TimeZone.getDefault();
return new Date(0 - default1.getOffset(0l));
}
/**
* 根据开始时间和结束时间返回时间段内的时间集合
*
* @param beginDate
* @param endDate
* @return List
*/
public static List<Date> getDatesBetweenTwoDate(Date beginDate, Date endDate) {
List<Date> lDate = new ArrayList<Date>();
lDate.add(beginDate);// 把开始时间加入集合
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, 1);
// 测试此日期是否在指定日期之后
if (endDate.after(cal.getTime())) {
lDate.add(cal.getTime());
} else {
break;
}
}
lDate.add(endDate);// 把结束时间加入集合
return lDate;
}
/**
* 根据开始时间和结束时间返回时间段内的年月集合
*
* @param beginDate
* @param endDate
* @return List
*/
public static List<String> getMonthBetweenTwoDate(Date beginDate, Date endDate) {
List<String> lYearMonth = new ArrayList<String>();
lYearMonth.add(dateToString4(beginDate));// 把开始时间加入集合
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.MONTH, 1);
// 测试此日期是否在指定日期之后
if (endDate.after(cal.getTime())) {
lYearMonth.add(dateToString4(cal.getTime()));
} else {
break;
}
}
lYearMonth.add(dateToString4(endDate));// 把结束时间加入集合
return lYearMonth;
}
/**
* 根据数字转换成对应的星期
*/
public static String getWeekDaysCn(String str) {
String week = "";
char[] chars = str.toCharArray();
for (char c : chars) {
if ("0".equals(String.valueOf(c))) {
week += "日";
}
if ("1".equals(String.valueOf(c))) {
week += "一";
}
if ("2".equals(String.valueOf(c))) {
week += "二";
}
if ("3".equals(String.valueOf(c))) {
week += "三";
}
if ("4".equals(String.valueOf(c))) {
week += "四";
}
if ("5".equals(String.valueOf(c))) {
week += "五";
}
if ("6".equals(String.valueOf(c))) {
week += "六";
}
}
return week;
}
/**
* 根据当前日期获取N天后的日期
*
* @return
*/
public static Date getDateByTaDay(Date date, int number) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, number);
Date nextDay = calendar.getTime();
return nextDay;
}
public static String Min2HHmmss(long mins) {
String HHmmss = "";
if (mins <= 0) {
HHmmss = "00:00:00";
}
long hour = mins / 60;
long min = mins - hour * 60;
String hourStr = String.valueOf(hour);
String minStr = String.valueOf(min);
if (hour < 10) {
hourStr = "0" + hourStr;
}
if (min < 10) {
minStr = "0" + minStr;
}
HHmmss = hourStr + ":" + minStr + ":00";
return HHmmss;
}
public static Long HHmmss2Min(String mins) {
String[] minStr = mins.split(":");
return Long.valueOf(Integer.parseInt(minStr[0]) * 60 + Integer.parseInt(minStr[1]));
}
/**
* 获取日期所在周次 201709/201749
*
* @param date
* @return
*/
public static int getWeeksWithYearByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int weeks = getWeeksByDate(date);
String weekStr = "";
if (weeks < 10) {
weekStr = "0" + weeks;
} else {
weekStr = String.valueOf(weeks);
}
return Integer.valueOf(year + weekStr);
}
/**
* 获取日期所在周次 9、32
*
* @param date
* @return
*/
public static int getWeeksByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.setTime(date);
int weeks = calendar.get(Calendar.WEEK_OF_YEAR);
return weeks;
}
/**
* 功能:获取日期对应的星期中文名
*
* @param date
* @return
*/
public static String getWeekDayCnOfDate(Date date) {
return weekDays.get(getWeekDayOfDate(date));
}
/**
* 取得给定时间对应的星期
*
* @return
*/
public static String getWeekDayOfDate(Date date) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
return "" + (c.get(Calendar.DAY_OF_WEEK) - 1);
}
/**
* 获取某周的第一天
*
* @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.setFirstDayOfWeek(Calendar.MONDAY);
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());
}
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();
}
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();
}
public static int getDayOfWeek(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
if (instance.get(Calendar.DAY_OF_WEEK) - 1 == 0) {
return 7;
} else {
return instance.get(Calendar.DAY_OF_WEEK) - 1;
}
}
public static int getDayOfWeek(String dateStr, String pattern) {
Date date = stringToDate(dateStr, pattern);
Calendar instance = Calendar.getInstance();
instance.setTime(date);
if (instance.get(Calendar.DAY_OF_WEEK) - 1 == 0) {
return 7;
} else {
return instance.get(Calendar.DAY_OF_WEEK) - 1;
}
}
/**
* 求两个日期差
*
* @param beginDate
* 开始日期
* @param endDate
* 结束日期
* @return 两个日期相差天数
*/
public static Long getDateInterval(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
return -1L;
}
long interval = endDate.getTime() - startDate.getTime();
return interval / (1000 * 60 * 60 * 24);
}
/**
* 计算两个日期之间相隔的数量,如天数,月数。。。具体由field决定
*
* @param after
* @param before
* @param field
* 参考Calendar.YEAR...
* @return
*/
public static int getDateInterval(java.util.Date after, java.util.Date before, int field) {
if (after == null || before == null) {
return 0;
}
Calendar calAfter = Calendar.getInstance();
calAfter.setTime(after);
Calendar calBefore = Calendar.getInstance();
calBefore.setTime(before);
return calAfter.get(field) - calBefore.get(field);
}
/**
* 功能:求两个日期相差小时数
*
* @param startDate
* @param endDate
* @return
*/
public static Long getHourInterval(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
return -1L;
}
long interval = endDate.getTime() - startDate.getTime();
return interval / (1000 * 60 * 60);
}
/**
* 求两个日期差(分钟)
*
* @param beginDate
* 开始日期
* @param endDate
* 结束日期
* @return 两个日期相差分钟
*/
public static Long getMinuteInterval(Date startDate, Date endDate) {
long interval = Math.abs(endDate.getTime() - startDate.getTime());
return interval / (1000 * 60);
}
/**
* 求两个日期差(分钟)
*
* * @param date 开始日期
*
* @return 两个日期相差分钟
*/
public static Long dateToMinute(Date date) {
String s = dateToString(date, "yyyy-MM-dd");
Date date1 = stringToDate(s);
return getMinuteInterval(date1, date);
}
/**
* 功能:获取不带时分秒的时间
*
* @param sourceDate
* @return
*/
public static Date getShortDate(Date sourceDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(sourceDate);
try {
return dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 功能:返回当前月份第一天
*
* @return
*/
public static Date getCurrentMonthFristDay() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* 功能:返回当前月份最后一天
*
* @return
*/
public static Date getCurrentMonthLastDay() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
/**
* 功能:返回当前月份最后一天
*
* @return
*/
public static Date getNextMonthLastDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
/**
* 获取日期所在周的七天(周一开始)
*
* @return
*/
public static String[] getWeekDatesStr(Date date) {
HashMap<String, Date> dateMap = getWeekDates(date);
List<Date> dateList = new ArrayList<Date>(dateMap.values());
String[] datesStr = new String[dateList.size()];
for (int i = 0; i < dateList.size(); i++) {
datesStr[i] = dateToString(dateList.get(i), "yyyy-MM-dd");
}
return datesStr;
}
/**
* 功能:返回参数所在星期的7天, 如,传入日期'2011-06-02'(星期四), 则返回20011-06-02所在星期的周日至周一的日期Map:
* {(SUN:'2011-05-29'),(MON:'2011-05-30'),(TUE:'2011-05-31'),(WED:'2011-06-01'),(THU:'2011-06-02'),(FRI:'2011-06-03',(SAT:'2011-06-04')}
*
* @param date
* @return
*/
public static HashMap<String, Date> getWeekDates(Date date) {
HashMap<String, Date> dates = new HashMap<String, Date>();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setFirstDayOfWeek(Calendar.MONDAY);
int index = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK, (-1) * (index - 1));
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("MON", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("TUE", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("WED", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("THU", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("FRI", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("SAT", c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
dates.put("SUN", c.getTime());
return dates;
}
// 计算当月有多少天
public static int days(int year, int month) {
int days = 0;
if (month != 2) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
}
} else {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
}
return days;
}
/**
* 功能: 取传入参数日期的当月第一天
*
* @param date
* @return
*/
public static Date getMonthFirstDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 功能: 取传入参数日期的当月最后一天
*
* @param date
* @return
*/
public static Date getMonthLastDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.add(Calendar.DAY_OF_YEAR, -1);
return cal.getTime();
}
/**
* 功能: 平移月份
*
* @param date
* @param monthNum
* @return
*/
public static Date moveDate(Date date, int monthNum) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, monthNum);
return cal.getTime();
}
/**
* 功能: 根据days参数移动日期,days可为正 可为负 日期去除时分秒
*
* @param date
* @param days
* @return
*/
public static Date moveDay(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, days);
return cal.getTime();
}
/**
* 获取当前日期,不带时分秒
*
* @return
*/
public static Date getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return parseString(sdf.format(new Date()));
}
public static Date parseString(String strDate) {
if (StringUtils.isNotBlank(strDate)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static Date parseString(String strDate, String format) {
if (StringUtils.isNotBlank(strDate)) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 分钟转小时
*
* @param min
* @return
*/
public static String minToHour(int min) {
if (min == 0) {
return "0";
}
int hour = min / 60;
int leftMin = min % 60;
String minStr = leftMin < 10 ? "0" + leftMin : leftMin + "";
return hour + ":" + minStr;
}
/**
* 功能: 判断两个日期的间隔天数是否超过参数值 超过返回true 未超过返回false
*
* @param beforeDate
* 前一日期
* @param lastDate
* 后一日期
* @param days
* 间隔天数
* @return
*/
public static Boolean checkDistanceDay(Date beforeDate, Date lastDate, int days) {
long interval = 0L;
if (beforeDate.before(lastDate)) {
interval = lastDate.getTime() - beforeDate.getTime();
} else {
interval = beforeDate.getTime() - lastDate.getTime();
}
int betweenDays = (int) (interval / (1000 * 60 * 60 * 24));
if (betweenDays > days) {
return true;
} else {
return false;
}
}
/**
* 功能:平移小时
*
* @param date
* @param hour
* @return
*/
public static Date moveHour(Date date, int hour) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hour);
return cal.getTime();
}
/**
* 功能:平移分钟
*
* @param date
* @param hour
* @return
*/
public static Date moveMinute(Date date, int minute) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, minute);
return cal.getTime();
}
/**
* 功能:获取Date中某个属性的值
*
* @param date
* @param field
* java.util.Calendar类中定义
* @return
*/
public static int getDateField(Date date, int field) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(field);
}
/**
* 功能: 根据参数years平移年份
*
* @param date
* @param years
* @return
*/
public static Date moveYear(Date date, int years) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, years);
return cal.getTime();
}
/**
* 功能:根据年份获得这年的最后一天
*
* @param year
* @return
*/
public static Date getLastDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, 11, 31);
return cal.getTime();
}
/**
* 功能:根据年份获得这年的第一天
*
* @param year
* @return
*/
public static Date getFirstDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, 0, 1);
return cal.getTime();
}
/**
* 功能:返回指定年度指定季度的第一天
*
* @param quarter,{1,2,3,4}
* @param year
* @return
*/
public static Date qetQuarterFirstDay(int quarter, int year) {
String firstDateStr = null;
Date firstDate = null;
if (year > 0) {
if (quarter >= 1 && quarter <= 4) {
switch (quarter) {
case 1: {
firstDateStr = year + "-01-01";
break;
}
case 2: {
firstDateStr = year + "-04-01";
break;
}
case 3: {
firstDateStr = year + "-07-01";
break;
}
case 4: {
firstDateStr = year + "-10-01";
break;
}
default:
;
}
}
}
if (firstDateStr != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
firstDate = sdf.parse(firstDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
return firstDate;
}
/**
* 功能:返回指定年度指定季度的最后一天
*
* @param quarter
* @param year
* @return
*/
public static Date getQuarterLastDay(int quarter, int year) {
Date quarterFirstDay = qetQuarterFirstDay(quarter, year);
if (quarterFirstDay != null) {
return getQuarterLastDay(quarterFirstDay);
} else {
return null;
}
}
/**
* 功能:返回参数日期所在季度第一天
*
* @param date
* @return
*/
public static Date getQuarterFirstDay(Date date) {
int year = getDateField(date, Calendar.YEAR);
int quarter = getQuarter(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
switch (quarter) {
case 1: {
c.set(Calendar.MONTH, 0);
break;
}
case 2: {
c.set(Calendar.MONTH, 3);
break;
}
case 3: {
c.set(Calendar.MONTH, 6);
break;
}
case 4: {
c.set(Calendar.MONTH, 9);
break;
}
default:
;
}
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* 功能:返回参数日期所在季度最后一天
*
* @param date
* @return
*/
public static Date getQuarterLastDay(Date date) {
int year = getDateField(date, Calendar.YEAR);
int quarter = getQuarter(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
switch (quarter) {
case 1: {
c.set(Calendar.MONTH, 3);
break;
}
case 2: {
c.set(Calendar.MONTH, 6);
break;
}
case 3: {
c.set(Calendar.MONTH, 9);
break;
}
case 4: {
c.set(Calendar.YEAR, year + 1);
c.set(Calendar.MONTH, 0);
break;
}
default:
;
}
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DAY_OF_YEAR, -1);
return c.getTime();
}
/**
* 功能:返回参数日期所在季度, 1:第一季度 2:第二季度 3:第三季度 4:第四季度
*
* @param date
* @return
*/
public static int getQuarter(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
switch (month) {
case 0:
return 1;
case 1:
return 1;
case 2:
return 1;
case 3:
return 2;
case 4:
return 2;
case 5:
return 2;
case 6:
return 3;
case 7:
return 3;
case 8:
return 3;
case 9:
return 4;
case 10:
return 4;
case 11:
return 4;
default:
;
}
return -1;
}
/**
* @param stringDate
* @return
* @throws ParseException
* @description:String转换为Date pattern
*/
public static Date stringToDate(String stringDate, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = null;
try {
date = sdf.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* @param stringDate
* @return
* @throws ParseException
* @description:String转换为Date yyyy-MM-dd
*/
public static Date stringToDate(String stringDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* @param stringDate
* @return
* @throws ParseException
* @description:String转换为Date yyyy-MM-dd
*/
public static String dateToString(Date formatDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (null == formatDate) {
return null;
}
String date = sdf.format(formatDate);
return date;
}
/**
* @param stringDate
* @return
* @throws ParseException
* @description:String转换为Date yyyy-MM
*/
public static String dateToString2(Date formatDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
if (null == formatDate) {
return null;
}
String date = sdf.format(formatDate);
return date;
}
/**
* @param stringDate
* @return
* @throws ParseException
* @description:date转换为String yyyy年MM月dd日 hh:mm:ss
*/
public static String dateToString3(Date Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
String dateString = null;
try {
dateString = sdf.format(Date);
} catch (Exception e) {
e.printStackTrace();
}
return dateString;
}
public static String dateToString4(Date Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String dateString = null;
try {
dateString = sdf.format(Date);
} catch (Exception e) {
e.printStackTrace();
}
return dateString;
}
/**
* 格式化日期
*
* @param Date
* @param pattern
* @return
*/
public static Date formatDate(Date Date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String dateString = null;
Date date = null;
try {
dateString = sdf.format(Date);
date = stringToDate(dateString, pattern);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/**
* 获取一天的起始时间
*
* @param date
*/
public static Date getDayFirstTime(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);
return cal.getTime();
}
/**
* 获取一天的结束时间
*
* @param date
* @return
*/
public static Date getDayLastTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
/**
* 获取一天的起始时间
*
* @param date
*/
public static Date getDayFirstTimeForTimingSheet(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 获取一天的结束时间
*
* @param date
* @return
*/
public static Date getDayLastTimeForTimingSheet(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date stringToDates(String str) throws Exception {
DateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss 'UTC'Z yyyy", Locale.ENGLISH);
Date date = df.parse(str);
return date;
}
/**
* 获取当前时间戳
*
* @return
*/
public static String getCurrentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date);
return str;
}
public static String dateToString(Date date, String pattern) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String result = sdf.format(date);
return result;
}
return "";
}
public static Date getDate(Date date, int intervalDay) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_YEAR, intervalDay);
return c.getTime();
}
public static Date getIntervalMonthLastDay(Date date, int intervalMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, intervalMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
return c.getTime();
}
public static Date getIntervalMonthMinDay(Date date, int intervalMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, intervalMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 15);
return c.getTime();
}
/**
* @param smdate
* @param bdate
* @return
* @throws ParseException
*/
public static int daysBetween(Date startDate, Date endDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
startDate = sdf.parse(sdf.format(startDate));
endDate = sdf.parse(sdf.format(endDate));
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
long time1 = cal.getTimeInMillis();
cal.setTime(endDate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
System.out.println(between_days);
return Integer.parseInt(String.valueOf(between_days)) + 1;
}
/**
* 字符串的日期格式的计算
*/
public static int daysBetween(String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days)) + 1;
}
/**
* 把分钟转换为小时显示,格式如:2:50表示2小时50分钟
*
* @param mins
* @return
*/
public static String formatMinutes2Hours(Long mins) {
if (mins == null || mins.longValue() == 0) {
return "0";
}
return (mins / 60 < 10 ? "0" + mins / 60 : mins / 60) + ":" + StringUtils.leftPad("" + mins % 60, 2, "0");
}
/**
* @param beginDate
* @param endDate
* @return
*/
public static long getMillisInterval(Date beginDate, Date endDate) {
return endDate.getTime() - beginDate.getTime();
}
/**
* @param beginDate
* @param endDate
* @return
*/
public static long getSecondsInterval(Date beginDate, Date endDate) {
return (endDate.getTime() - beginDate.getTime()) / 1000;
}
/**
* 删除给定Date的时分秒毫秒
*
* @param now
* @return
*/
public static Date truncateTimeOfDate(Date now) {
if (now == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
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();
}
/**
* 给定的日期加上addTime的时间
*
* @param now
* @param addTime
* 毫秒
* @return
*/
public static Date addDate(java.util.Date now, long addTime) {
if (now == null) {
return null;
}
return new java.util.Date(now.getTime() + addTime);
}
public static Date addDateYear(Date now, int yearCount) {
return addDate(now, yearCount, 0, 0, 0, 0, 0, 0);
}
public static Date addDate(java.util.Date now, int year, int month, int day, int hour, int minute, int second,
int millSecond) {
if (now == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.YEAR, year);
c.add(Calendar.MONTH, month);
c.add(Calendar.DATE, day);
c.add(Calendar.HOUR_OF_DAY, hour);
c.add(Calendar.MINUTE, minute);
c.add(Calendar.SECOND, second);
c.add(Calendar.MILLISECOND, millSecond);
return c.getTime();
}
public static Date addDate(java.util.Date now, int year, int month, int day, int hour, int minute, int second) {
return addDate(now, year, month, day, hour, minute, second, 0);
}
public static Date addDate(java.util.Date now, int hour, int minute, int second) {
return addDate(now, 0, 0, 0, hour, minute, second, 0);
}
public static Date addDateField(java.util.Date now, int field, int amount) {
if (now == null) {
return null;
}
if (amount == 0) {
return now;
}
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(field, amount);
return c.getTime();
}
/**
* 功能:获取两个日期之间的所有日期
*
* @param startDate
* 开始日期
* @param endDate
* 结束日期
* @return
*/
public static List<Date> getIntervalDates(Date startDate, Date endDate) {
List<Date> result = new ArrayList<Date>();
Long intervalDay = getDateInterval(DateUtils.truncateTimeOfDate(startDate),
DateUtils.truncateTimeOfDate(endDate));
if (intervalDay < 0) {
return result;
}
for (Long i = 0L; i <= intervalDay; i++) {
Date currentDate = addDateField(startDate, Calendar.DATE, i.intValue());
result.add(currentDate);
}
return result;
}
public static int getDOW(String date) {
int result = 0;
try {
if (StringUtils.isNotBlank(date)) {
Date tmp = new SimpleDateFormat("yyyyMMddHHmm").parse(date);
result = new DateTime(tmp).dayOfWeek().get();
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static String getLocalTime(String localTimeStr, int timeZone) {
String timeZoneStr = "";
if (timeZone < 0) {
if (Math.abs(timeZone) < 10) {
timeZoneStr = "-0" + Math.abs(timeZone) + ":00";
} else {
timeZoneStr = "-" + Math.abs(timeZone) + ":00";
}
} else {
if (timeZone < 10) {
timeZoneStr = "+0" + timeZone + ":00";
} else {
timeZoneStr = "+" + timeZone + ":00";
}
}
String result = null;
try {
Date tmp = new SimpleDateFormat("yyyyMMddHHmm").parse(localTimeStr);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tmp).replaceAll(" ", "T");
result = format + timeZoneStr;
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static String getGMTTime(String gmtTimeStr) {
String result = null;
try {
Date tmp = new SimpleDateFormat("yyyyMMddHHmm").parse(gmtTimeStr);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tmp).replaceAll(" ", "T");
result = format + "+00:00";
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static boolean isContinuityDay(String beginDate, String endDate, String pattern) {
Date dateBegin = stringToDate(beginDate, pattern);
Calendar instance = Calendar.getInstance();
instance.setTime(dateBegin);
instance.add(Calendar.DAY_OF_MONTH, 1);
Date dateAddOne = instance.getTime();
return dateToString(dateAddOne, pattern).equals(endDate);
}
public static Integer getDowByLocalDateTime(String dateTimeStr) {
DateTime dateTime = new DateTime(dateTimeStr);
return dateTime.getDayOfWeek();
}
public static String getTimeByLocalDateTime(String dateTimeStr) {
DateTime dateTime = new DateTime(dateTimeStr);
return new SimpleDateFormat("HHmm").format(dateTime.toDate());
}
public static String formatPekDateFromGMTString(String gmtString) {
DateTime dateTime = new DateTime(gmtString, DateTimeZone.forOffsetHours(8));
return dateTime.toString("yyyy-MM-dd HH:mm");
}
public static String formatPekDateFromGMTString(String gmtString, String pattern) {
DateTime dateTime = new DateTime(gmtString, DateTimeZone.forOffsetHours(8));
return dateTime.toString(pattern);
}
public static String formatPekDateFromGMTNoTime(String gmtString, String pattern) {
DateTime dateTime = new DateTime(gmtString, DateTimeZone.forOffsetHours(8));
return dateTime.toString(pattern);
}
public static int getSlot(String dateTime, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date;
try {
date = sdf.parse(dateTime);
SimpleDateFormat hh = new SimpleDateFormat("HH");
String format = hh.format(date);
return Integer.parseInt(format);
} catch (ParseException e) {
System.out.println("getSlot parser accourred an exception: " + e.getMessage());
}
return -1;
}
/**
* 给定时间段和星期几,计算该时间段内共有多少个给定的星期几
*
* @param start
* 开始时间,格式yyyy-MM-dd
* @param end
* 结束时间,格式yyyy-MM-dd
* @param a
* 星期几,从星期一到星期天,分别用数字1-7表示
* @return 星期几统计数
*/
public static long weekend(Date start, Date end, int a) {
// 计数
long sunDay = 0;
try {
// 开始时间
Calendar startDate = Calendar.getInstance();
startDate.setTime(start);
// 结束时间
Calendar endDate = Calendar.getInstance();
endDate.setTime(end);
// 开始日期是星期几
int SW = startDate.get(Calendar.DAY_OF_WEEK) - 1;
// 结束日期是星期几
int EW = endDate.get(Calendar.DAY_OF_WEEK) - 1;
long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
// 给定时间段内一共有多少天
long days = diff / (1000 * 60 * 60 * 24);
// 给定时间内,共有多少个星期
long w = Math.round(Math.ceil(((days + SW + (7 - EW)) / 7.0)));
// 总的星期几统计数
sunDay = w;
if (a != 7) {
// 给定的星期几小于起始日期的星期几,需要减少一天
if (a < SW) {
sunDay--;
}
// 给定的星期几大于结束日期的星期几,需要减少一天
if (a > EW) {
sunDay--;
}
}
} catch (Exception se) {
se.printStackTrace();
}
return sunDay;
}
public static Date addDays(Date date, int days) {
return DateUtils.addDateField(date, Calendar.DATE, days);
}
public static void main(String[] args) {
Date zeroHourMinute = getZeroHourMinute();
System.out.println(zeroHourMinute);
System.out.println(zeroHourMinute.getTime());
}
}
EasyExcelUtils Excel操作工具类
readExcel 解析excel
package com.yhl.ros.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;
/**
* @ClassName: EasyExcelUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:09
*/
public class EasyExcelUtils {
/**
* 下载EXCEL文件2007版本
*
* @throws IOException
* IO异常
*/
public static void exportExcel2007Format(EasyExcelParams excelParams) throws IOException {
exportExcel(excelParams, ExcelTypeEnum.XLSX);
}
/**
* 下载EXCEL文件2003版本
*
* @throws IOException
* IO异常
*/
public static void exportExcel2003Format(EasyExcelParams excelParams) throws IOException {
exportExcel(excelParams, ExcelTypeEnum.XLS);
}
/**
* 根据参数和版本枚举导出excel文件
*
* @param excelParams
* 参数实体
* @param typeEnum
* excel类型枚举
* @throws IOException
*/
private static void exportExcel(EasyExcelParams excelParams, ExcelTypeEnum typeEnum) throws IOException {
Validate.isTrue(excelParams.isValid(), "easyExcel params is not valid");
HttpServletResponse response = excelParams.getResponse();
ServletOutputStream out = response.getOutputStream();
ExcelWriter writer = new ExcelWriter(out, typeEnum, excelParams.isNeedHead());
prepareResponds(response, excelParams.getExcelNameWithoutExt(), typeEnum);
Sheet sheet1 = new Sheet(1, 0, excelParams.getDataModelClazz());
if (StringUtils.isNotBlank(excelParams.getSheetName())) {
sheet1.setSheetName(excelParams.getSheetName());
}
writer.write(excelParams.getData(), sheet1);
writer.finish();
out.flush();
}
/**
* 将文件输出到浏览器(导出文件)
*
* @param response
* 响应
* @param fileName
* 文件名(不含拓展名)
* @param typeEnum
* excel类型
*/
private static void prepareResponds(HttpServletResponse response, String fileName, ExcelTypeEnum typeEnum) {
String fileName2Export = new String((fileName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-disposition", "attachment;filename=" + fileName2Export + typeEnum.getValue());
}
public static <E> List<E> readExcel1(Workbook workbook, Class<E> clazz)
throws IllegalAccessException, InstantiationException {
List<E> datas = new ArrayList<E>();
// 得到工作簿开始解析数据
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
if (sheet != null) {
List<String> headers = new ArrayList<>();
Row tableHead = sheet.getRow(0);
int index = 0;
while (true) {
Cell cell = tableHead.getCell(index);
if (cell == null) {
break;
}
String value = cell.getStringCellValue();
headers.add(value);
index++;
}
String[] list = { "目的地", "订单号", "目的地址", "发货人", "收货人" };
List<String> mustHeaders = Arrays.asList(list);
if (!headers.containsAll(mustHeaders)) {
return null;
}
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
if (row == null)
continue;
E data = clazz.newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field fied : declaredFields) {
ExcelProperty annotation = fied.getAnnotation(ExcelProperty.class);
if (annotation == null) {
continue;
}
String value = annotation.value()[0];
for (int j = 0; j < headers.size(); j++) {
String header = headers.get(j);
if (header.equals(value)) {
try {
Class<?> type = fied.getType();
fied.setAccessible(true);
if (row.getCell(j) != null) {
if (type.equals(String.class)) {
if (row.getCell(j).getCellTypeEnum() == CellType.STRING) {
fied.set(data, row.getCell(j).getStringCellValue());
} else if (row.getCell(j).getCellTypeEnum() == CellType.NUMERIC) {
fied.set(data, row.getCell(j).getNumericCellValue() + "");
}
} else if (type.equals(Double.class)) {
fied.set(data, row.getCell(j).getNumericCellValue());
} else if (type.equals(Date.class)) {
try {
fied.set(data, row.getCell(j).getDateCellValue());
} catch (IllegalStateException ex) {
fied.set(data, DateUtils.parseString(row.getCell(j).getStringCellValue(),
"yyyy/MM/dd HH:mm"));
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
datas.add(data);
}
}
return datas;
}
public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
Workbook workbook = null;
if (fileType.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (fileType.equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
}
public static <E> List<E> readExcel(Workbook workbook, Class<E> clazz, Integer dataBeginRow)
throws IllegalAccessException, InstantiationException {
List<E> datas = new ArrayList<E>();
// 得到工作簿开始解析数据
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
if (sheet != null) {
List<String> headers = new ArrayList<>();
Row tableHead = sheet.getRow(0);
int index = 0;
while (true) {
Cell cell = tableHead.getCell(index);
if (cell == null) {
break;
}
String value = cell.getStringCellValue();
headers.add(value);
index++;
}
int lastRowNum = sheet.getLastRowNum();
for (int i = dataBeginRow; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
Cell cell = row.getCell(0);
if (cell == null) {
continue;
}
cell.setCellType(CellType.STRING);
if (StringUtils.isBlank(cell.getStringCellValue())) {
continue;
}
E data = clazz.newInstance();
List<Field> declaredFields = Lists.newArrayList(clazz.getDeclaredFields()).stream().sorted((t1,t2) -> {
return t1.getName().compareTo(t2.getName());
}).collect(Collectors.toList());
Map<String, Double> loadCosts = new HashMap<>();
for (Field field : declaredFields) {
field.setAccessible(true);
ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
if (annotation == null) {
field.set(data, loadCosts);
} else {
String value = annotation.value()[0];
for (int j = 0; j < headers.size(); j++) {
String header = headers.get(j);
Cell _cell = row.getCell(j);
if (null != _cell) {
_cell.setCellType(CellType.STRING);
}
if (header.equals(value)) {
try {
Class<?> type = field.getType();
if (_cell != null) {
if (type.equals(String.class)) {
field.set(data, _cell.getStringCellValue());
} else if (type.equals(Double.class)) {
field.set(data, Double.parseDouble(_cell.getStringCellValue()));
} else if (type.equals(Long.class)) {
field.set(data, Long.parseLong(_cell.getStringCellValue()));
} else if (type.equals(Date.class)) {
field.set(data, DateUtils.parseString(_cell.getStringCellValue(), "yyyyMMdd"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
if (header.startsWith("KBETR")) {
loadCosts.put(header, Double.parseDouble(_cell.getStringCellValue()));
}
}
}
}
}
datas.add(data);
}
}
return datas;
}
public static void main(String[] args) {
double xx = 22.0;
long yy = 22;
if (xx == yy) {
System.out.println(true);
} else {
System.out.println(false);
}
}
public static class EasyExcelParams {
/**
* excel文件名(不带拓展名)
*/
private String excelNameWithoutExt;
/**
* sheet名称
*/
private String sheetName;
/**
* 是否需要表头
*/
private boolean needHead = true;
/**
* 数据
*/
private List<? extends BaseRowModel> data;
/**
* 数据模型类型
*/
private Class<? extends BaseRowModel> dataModelClazz;
/**
* 响应
*/
private HttpServletResponse response;
public EasyExcelParams() {
}
/**
* 检查不允许为空的属性
*/
public boolean isValid() {
return ObjectUtils.allNotNull(excelNameWithoutExt, data, dataModelClazz, response);
}
public String getExcelNameWithoutExt() {
return excelNameWithoutExt;
}
public void setExcelNameWithoutExt(String excelNameWithoutExt) {
this.excelNameWithoutExt = excelNameWithoutExt;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public boolean isNeedHead() {
return needHead;
}
public void setNeedHead(boolean needHead) {
this.needHead = needHead;
}
public List<? extends BaseRowModel> getData() {
return data;
}
public void setData(List<? extends BaseRowModel> data) {
this.data = data;
}
public Class<? extends BaseRowModel> getDataModelClazz() {
return dataModelClazz;
}
public void setDataModelClazz(Class<? extends BaseRowModel> class1) {
this.dataModelClazz = class1;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}
}
EnumUtil 枚举工具类
getEnumBycode 返回指定编码的’枚举’
getEnumByDesc 返回指定描述的’枚举’
getCodeByDesc 根据描述获取code
getDescByCode 根据代码获取描述
getEnumValueList 枚举值转换成 List (主要下拉框使用)
package com.yhl.ros.common.utils;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;
import com.yhl.ros.common.LabelValue;
import com.yhl.ros.common.enums.CommonEnum;
/**
* @ClassName: EnumUtil
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:09
*/
public class EnumUtil<T> {
/**
* 返回指定编码的'枚举' @param code @return Enum @throws
*/
public static <T extends CommonEnum> T getEnumBycode(Class<T> clazz, String code) {
if (StringUtils.isEmpty(code)) {
return null;
}
for (T _enum : clazz.getEnumConstants()) {
if (code.equals(_enum.getCode())) {
return _enum;
}
}
return null;
}
/**
* 返回指定描述的'枚举' @param desc @return Enum @throws
*/
public static <T extends CommonEnum> T getEnumByDesc(Class<T> clazz, String desc) {
if (StringUtils.isEmpty(desc)) {
return null;
}
for (T _enum : clazz.getEnumConstants()) {
if (_enum.getDesc().equals(desc)) {
return _enum;
}
}
return null;
}
/**
* 根据代码获取描述
*
* @param clazz
* @param code
* @return
*/
public static <T extends CommonEnum> String getDescByCode(Class<T> clazz, String code) {
if (StringUtils.isEmpty(code)) {
return null;
}
T t = getEnumBycode(clazz, code);
if (null != t) {
return t.getDesc();
}
return null;
}
/**
* 根据描述获取code
*
* @param clazz
* @param desc
* @return
*/
public static <T extends CommonEnum> String getCodeByDesc(Class<T> clazz, String desc) {
if (StringUtils.isEmpty(desc)) {
return null;
}
T t = getEnumByDesc(clazz, desc);
if (null != t) {
return t.getCode();
}
return null;
}
/**
* 枚举值转换成 List (主要下拉框使用)
*
* @param clazz
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends CommonEnum> List<LabelValue> getEnumValueList(Class<T> clazz) {
if (StringUtils.isEmpty(clazz)) {
return null;
}
List<LabelValue> labelValues = new ArrayList<LabelValue>();
for (T _enum : clazz.getEnumConstants()) {
LabelValue labelValue = new LabelValue();
labelValue.setValue(_enum.getCode());
labelValue.setLabel(_enum.getDesc());
labelValues.add(labelValue);
}
return labelValues;
}
}
ExcelExportUtils Excel导出工具类
package com.yhl.ros.common.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* @ClassName: ExcelExportUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:10
*/
public class ExcelExportUtils {
private static String SHEET_NAME = "sheet";
private WritableSheet sheet = null;
private WritableWorkbook workBook = null;
private int row;
private static final Log LOG = LogFactory.getLog(ExcelExportUtils.class);
public ExcelExportUtils() {
}
public ExcelExportUtils(OutputStream output) {
try {
workBook = Workbook.createWorkbook(output);
sheet = workBook.createSheet(SHEET_NAME, 0);
} catch (IOException e) {
LOG.error(e.getMessage());
}
}
public void closeBook() {
try {
workBook.write();
workBook.close();
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
/**
* 写入excel文件
*
* @param out
* 输出流
* @param labelNames
* 列名
* @param fields
* 对象属性
* @param values
* 对象
*/
public void writeExcel(ExcelTitle title, List<ExcelLabel> labels, String[] fields, List<? extends Object> values) {
try {
if (title != null) {
createTitle(sheet, title, getMaxColspan(labels));
}
if (!CollectionUtils.isEmpty(labels)) {
createLables(sheet, labels);
}
int rows = getMaxRow(labels);
for (Object object : values) {
++rows;
for (int i = 0; i < fields.length; i++) {
WritableCell cell = getCell(i, rows, object, fields[i]);
if (cell != null) {
sheet.addCell(cell);
}
}
}
this.row = rows + 2;
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
/**
* 创建标题
*
* @param sheet
* @param labels
* @throws WriteException
* @throws RowsExceededException
*/
private void createLables(WritableSheet sheet, List<ExcelLabel> labels)
throws RowsExceededException, WriteException {
for (int i = 0; i < labels.size(); i++) {
ExcelLabel label = labels.get(i);
sheet.addCell(
new Label(label.getColum() - 1, this.row + label.getRow(), label.getLabelName(), getLabelFormat()));
sheet.mergeCells(label.getColum() - 1, this.row + label.getRow(),
label.getColum() - 1 + (label.getColspan() - 1),
this.row + label.getRow() + (label.getRowspan() - 1));
sheet.setColumnView(label.getColum() - 1, 15);
}
}
/**
* 标题样式
*
* @return
* @throws WriteException
*/
private CellFormat getLabelFormat() throws WriteException {
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
WritableCellFormat wcfF = new WritableCellFormat(wf);
wcfF.setAlignment(Alignment.CENTRE);
wcfF.setBorder(Border.ALL, BorderLineStyle.THIN);
return wcfF;
}
/**
* 获取EXCEL单元格
*
* @param column
* 列
* @param row
* 行
* @param object
* 对象
* @param fieldName
* 对象属性
* @return
*/
private WritableCell getCell(int column, int row, Object object, String fieldName) {
try {
Field field = null;
try {
field = object.getClass().getDeclaredField(fieldName);
} catch (Exception e) {
field = object.getClass().getField(fieldName);
}
if (field == null) {
LOG.warn("field 不存在");
return null;
}
BeanWrapper bw = new BeanWrapperImpl(object);
Object value = bw.getPropertyValue(fieldName);
// return new Label(column, row, value.toString());
// String value = BeanUtils.getProperty(object, fieldName);
String fieldType = field.getType().getName();
if (value != null) {
if (fieldType.equalsIgnoreCase(Integer.class.getName()) || fieldType.equalsIgnoreCase("int")
|| fieldType.equalsIgnoreCase(Short.class.getName())
|| fieldType.equalsIgnoreCase(Long.class.getName())
|| fieldType.equalsIgnoreCase(Float.class.getName())
|| fieldType.equalsIgnoreCase(Double.class.getName())
|| fieldType.equalsIgnoreCase(Byte.class.getName())) {
return new Number(column, row, Double.parseDouble(value.toString()), getContentFormat());
} else if (fieldType.equalsIgnoreCase("java.util.Date")) {
// Date dateValue = (Date)field.get(object);
// return null;
return new Label(column, row, CommonDateUtils.dateToString((Date) value), getContentFormat());
} else {
return new Label(column, row, value.toString(), getContentFormat());
}
}
// 为了保证数据为空时,表格样式一致
return new Label(column, row, null, getContentFormat());
} catch (Exception e) {
LOG.error(e.getMessage());
}
return null;
}
/**
* 内容样式
*
* @return
* @throws WriteException
*/
private CellFormat getContentFormat() throws WriteException {
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat wcfF = new WritableCellFormat(wf);
wcfF.setBorder(Border.ALL, BorderLineStyle.THIN);
return wcfF;
}
/**
* 计算最大列宽
*
* @param labels
* @return
*/
private int getMaxColspan(List<ExcelLabel> labels) {
ExcelLabel maxColLabel = null;
for (ExcelLabel excelLabel : labels) {
if (maxColLabel == null) {
maxColLabel = excelLabel;
} else {
if (maxColLabel.getColum() < excelLabel.getColum()) {
maxColLabel = excelLabel;
}
}
}
if (null != maxColLabel) {
return maxColLabel.getColum() + maxColLabel.getColspan() - 1;
}
return 0;
}
/**
* 创建标题
*
* @param sheet
* @param title
* @throws WriteException
* @throws RowsExceededException
*/
private void createTitle(WritableSheet sheet, ExcelTitle title, int clospan)
throws RowsExceededException, WriteException {
sheet.addCell(new Label(0, this.row, title.getTitle(), getTitleFormat()));
sheet.mergeCells(0, this.row, clospan - 1, this.row);
sheet.setRowView(row, 500);// 行高
}
/**
* 获取标题格式
*
* @return
* @throws WriteException
*/
private CellFormat getTitleFormat() throws WriteException {
WritableFont wf = new WritableFont(WritableFont.ARIAL, 18, WritableFont.BOLD, false);
WritableCellFormat wcfF = new WritableCellFormat(wf);
wcfF.setAlignment(Alignment.CENTRE);
wcfF.setBorder(Border.ALL, BorderLineStyle.THIN);
return wcfF;
}
/**
* 获取label占用几行
*
* @param labels
* @return
*/
private int getMaxRow(List<ExcelLabel> labels) {
int row = 0;
for (ExcelLabel excelLabel : labels) {
if (excelLabel.getRow() > row) {
row = excelLabel.getRow();
}
}
return row + this.row;
}
public void createSheet(String sheetName, int sort) {
this.row = 0;
sheet = workBook.createSheet(sheetName, sort);
}
public void setSheet(WritableSheet sheet) {
this.sheet = sheet;
}
public WritableWorkbook getWorkBook() {
return workBook;
}
public static void main(String[] args) throws FileNotFoundException {
}
}
ExcelLabel Excel标签工具类
package com.yhl.ros.common.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName: ExcelLabel
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExcelLabel {
private String labelName;
// 第几行
private int row = 1;
// 占几行
private int rowspan = 1;
// 第几列
private int colum;
// 占几列
private int colspan = 1;
public ExcelLabel(String labelName, int colum) {
this.labelName = labelName;
this.colum = colum;
}
}
ExcelTitle Excel标题工具类
package com.yhl.ros.common.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @ClassName: ExcelTitle
* @Package: com.yhl.ros.common.utils
* @Description: 报文标题
* @Date: 2020-02-12 01:12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExcelTitle {
// 标题
private String title;
// 行高
private int height;
public ExcelTitle(String title) {
this.title = title;
}
}
ExcelUtil Excel工具类
package com.yhl.ros.common.utils;
import java.text.DecimalFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
/**
* @ClassName: ExcelUtil
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:16
*/
public class ExcelUtil {
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
public static String getCellString(Cell cell) {
String cellValue = "";
DecimalFormat df = new DecimalFormat("#.##");
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getRichStringCellValue().getString().trim();
break;
case NUMERIC:
/*
* short format = cell.getCellStyle().getDataFormat();
*
* 14 yyyy-MM-dd / 2017/01/01 31 yyyy年m月d日
*
* Date date = null; if(format == 14 || format == 31){ date =
* HSSFDateUtil.getJavaDate(cell.getNumericCellValue()); } if(date == null) {
* cellValue = df.format(cell.getNumericCellValue()).toString(); }else {
* cellValue = CommonDateUtils.dateToString(date); }
*/
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 用于转化为日期格式
Date date = cell.getDateCellValue();
cellValue = CommonDateUtils.dateToString(date);
} else {
cellValue = df.format(cell.getNumericCellValue()).toString();
}
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
return cellValue;
}
}
ExcelUtils Excel工具类(增强)
package com.yhl.ros.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.poi.poifs.filesystem.FileMagic;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: ExcelUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:16
*/
@Slf4j
public final class ExcelUtils {
@SuppressWarnings("unchecked")
public static <T> List<T> readExcel(InputStream inputStream, Class<T> clazz, int headRowNumber) {
if (null == inputStream) {
log.error("InputStream can not be null!");
return new ArrayList<T>();
}
SyncReadListener listener = new SyncReadListener();
ReadSheet readSheet = new ReadSheet();
readSheet.setClazz(clazz);
readSheet.setHeadRowNumber(headRowNumber);
ExcelReader reader = EasyExcel.read(inputStream).registerReadListener(listener).build();
reader.read(readSheet);
reader.finish();
return (List<T>) listener.getList();
}
@SuppressWarnings("deprecation")
public static List<Object> readBySAX(InputStream inputStream, int sheetNumber, int headRowNumber) {
if (null == inputStream) {
log.error("InputStream can not be null!");
return new ArrayList<Object>();
}
Sheet sheet = new Sheet(sheetNumber, headRowNumber);
SyncReadListener excelListener = new SyncReadListener();
EasyExcelFactory.readBySax(inputStream, sheet, excelListener);
return excelListener.getList();
}
public static <T> void writeExcelWithSimpleHead(OutputStream outputStream, List<T> data, Class<T> clazz,
List<String> simpleHead) {
WriteSheet writeSheet = new WriteSheet();
writeSheet.setSheetNo(0);
// writeSheet.setSheetName(DateUtils.dateToString(new Date(),
// DateUtils.COMMON_DATE_STR5));
writeSheet.setClazz(clazz);
writeSheet.setNeedHead(true);
List<List<String>> head = simpleHead.stream().map(item -> Arrays.asList(item)).collect(Collectors.toList());
writeSheet.setHead(head);
ExcelWriter writer = EasyExcel.write(outputStream).build();
writer.write(data, writeSheet);
writer.finish();
}
public static ExcelTypeEnum suffixOfExcel(InputStream inputStream) {
try {
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if (FileMagic.OLE2.equals(fileMagic)) {
return ExcelTypeEnum.XLS;
}
if (FileMagic.OOXML.equals(fileMagic)) {
return ExcelTypeEnum.XLSX;
}
throw new IllegalArgumentException("Unrecongnized file type");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
FileUtils 文件操作工具类
package com.yhl.ros.common.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* @ClassName: FileUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:17
*/
public class FileUtils {
public static File getFile(String fileName) {
try {
String path = fileName;
File file = new File(path);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 读取文件内容
*
* @param file
* @return
*/
public static String readerFile(File file) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String readLine = br.readLine();
return readLine;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != br)
br.close();
if (null != fr)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 写入文件并覆盖原内容
*
* @param str
* @param file
*/
public static void writeFile(String str, File file) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file, false);
bw = new BufferedWriter(fw);
bw.write(str);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != bw)
bw.close();
if (null != fw)
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除文件或者文件夹
*
* @param file
* @return
*/
public static boolean delFile(File file) {
if (!file.exists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
delFile(f);
}
}
return file.delete();
}
/**
* 删除文件或者文件夹(排除需要过滤的)
*
* @param file
* 要删除的文件夹、文件
* @param filePath
* 需要过滤的 文件夹、文件
* @return
*/
public static boolean delWithOutFile(File file, File filePath) {
if (!file.exists() || !filePath.exists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (!f.getAbsolutePath().equals(filePath.getAbsolutePath())) {
delFile(f);
}
}
}
return file.delete();
}
public static void main(String[] args) {
File file = new File("C:\\Users\\lenovo\\Desktop\\rosteringValidator");
String name = "C:\\Users\\lenovo\\Desktop\\rosteringValidator\\2019-03-08";
delWithOutFile(file, new File(name));
}
}
FtpUtil Ftp工具类
package com.yhl.ros.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: FtpUtil
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:17
*/
@Slf4j
public class FtpUtil {
/**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
* @param ftpPassword
* FTP 登录密码
* @param ftpUserName
* FTP登录用户名
* @param ftpPort
* FTP端口 默认为21
* @return
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.warn("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
log.info("FTP连接成功。");
}
} catch (SocketException e) {
log.error("FtpUtil.getFTPClient.SocketException", e);
} catch (IOException e) {
log.error("FtpUtil.getFTPClient.IOException", e);
}
return ftpClient;
}
/**
* Description: 向FTP服务器上传文件
*
* @param ftpHost
* FTP服务器hostname
* @param ftpUserName
* 账号
* @param ftpPassword
* 密码
* @param ftpPort
* 端口
* @param ftpPath
* FTP服务器中文件所在路径 格式: ftptest/aa
* @param fileName
* ftp文件名称
* @param input
* 文件流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, String ftpPath,
String fileName, InputStream input) {
boolean success = false;
FTPClient ftpClient = null;
try {
int reply;
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return success;
}
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
ftpClient.storeFile(fileName, input);
input.close();
ftpClient.logout();
success = true;
} catch (IOException e) {
log.error("FtpUtil.uploadFile.IOException", e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
GsonUtils Gson工具类
JSON.toJSONString(对象)
SimpleDateFormat 日期格式转换 yyyy-MM-dd HH:mm:ss
DecimalFormat 数据格式转换 #.##
package com.yhl.ros.common.utils;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* @ClassName: GsonUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:18
*/
public class GsonUtils<T> {
private static Gson gson = null;
static {
GsonBuilder builder = new GsonBuilder();
gson = builder.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
}
public static String toJson(Object objec) {
return gson.toJson(objec);
}
public T fromJson(String json, Type type) {
return gson.fromJson(json, type);
}
public static JsonObject getJsonObject(String json) {
return new JsonParser().parse(json).getAsJsonObject();
}
}
HttpUtils Http工具类
package com.yhl.ros.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class HttpUtils {
private HttpUtils() {
}
public static String sendRequest(URI uri) throws IOException {
return sendRequest(uri, null);
}
public static String sendPostRequest(URI uri, String json) throws IOException {
HttpPost httpRequest = new HttpPost(uri);
httpRequest.addHeader("Content-type","application/json; charset=utf-8");
httpRequest.setHeader("Accept", "application/json");
httpRequest.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(40000).setConnectionRequestTimeout(30000)
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
if (httpRequest instanceof HttpPost) {
HttpEntity requestEntity = EntityBuilder.create().setText(json).build();
((HttpPost) httpRequest).setEntity(requestEntity);
}
String responseStr;
try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
HttpEntity responseEntity = httpResponse.getEntity();
responseStr = EntityUtils.toString(responseEntity);
}
return responseStr;
}
public static String sendRequest(URI uri, String json) throws IOException {
HttpRequestBase httpRequest = (json == null || json.isEmpty()) ? new HttpGet(uri) : new HttpPost(uri);
// httpRequest.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpRequest.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
httpRequest.addHeader("Content-type","application/json; charset=utf-8");
httpRequest.setHeader("Accept", "application/json");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(40000).setConnectionRequestTimeout(30000)
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
if (httpRequest instanceof HttpPost) {
HttpEntity requestEntity = EntityBuilder.create().setText(json).build();
((HttpPost) httpRequest).setEntity(requestEntity);
}
String responseStr;
try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
HttpEntity responseEntity = httpResponse.getEntity();
responseStr = EntityUtils.toString(responseEntity);
}
return responseStr;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty(HTTP.CONTENT_ENCODING, "UTF-8");
conn.setRequestProperty("Content-type","application/json; charset=utf-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
InetUtils Inet工具类
package com.yhl.ros.common.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: InetUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:18
*/
@Slf4j
public class InetUtils {
public static HttpServletRequest httpRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return request;
}
public static String remoteHost() {
String remoteHost = null;
HttpServletRequest request = httpRequest();
if (request != null) {
remoteHost = request.getRemoteHost();
}
return remoteHost;
}
public static String localHost() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.info(e.getMessage());
e.printStackTrace();
return null;
}
}
}
MapUtils Map工具类
package com.yhl.ros.common.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: MapUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:18
*/
@Slf4j
public class MapUtils {
// 235fe9aca7ac6d98c60c95981a09b854,fc18e8c4181cb9620c2625cca0e9927a,218d529ce14fa2eb19d691b00a1c726c
private static String[] keys = {"38e0dff65d068d0ac04993c61e66687c", "9a7d90423142a1a35048f934a4caa619", "916b32662484b98f84a3938684d4fc54", "221fb2e7a8341a3ef9ffdc259263aee3",
"d409b80e01694874c47963047d3ed7e9", "2194b717e34a25a9bb3312622b99bf4f", "7c522c2e0d862240c84ccd9be7985c33", "218d529ce14fa2eb19d691b00a1c726c",
"4c8eb2e5de4a5f63dd6de53c41c74c76", "fc18e8c4181cb9620c2625cca0e9927a", "218d529ce14fa2eb19d691b00a1c726c", "8dfdb8ddda399257e25d5231b98eab00",
"235fe9aca7ac6d98c60c95981a09b854"};
private static String key = "218d529ce14fa2eb19d691b00a1c726c";
// private static String danoneKey = "e003db9c35b251158b61311c40ed3650";
/**
* 阿里云api 根据经纬度获取地址
*
* @param longitude
* @param latitude
* @return
*/
public static String getAdd(String longitude, String latitude) {
StringBuffer sb = new StringBuffer();
sb.append("key=").append(key).append("&location=").append(longitude).append(",").append(latitude);
String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", sb.toString());
// log.info(res);
JSONObject jsonObject = JSONObject.parseObject(res);
JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.getString("regeocode"));
String add = jsonObject1.get("formatted_address").toString();
return add;
}
/**
* 阿里云api 根据经纬度获取所在城市
*
* @param longitude
* @param latitude
* @return
*/
public static String getCity(String longitude, String latitude) {
// log 大 lat 小
// 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + longitude + "," + latitude + "&type=010";
String res = "";
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(res);
JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("addrList"));
JSONObject j_2 = JSONObject.parseObject(jsonArray.get(0).toString());
String allAdd = j_2.getString("admName");
String arr[] = allAdd.split(",");
res = arr[1];
} catch (Exception e) {
log.error("error in wapaction,and e is " + e.getMessage());
}
// log.info(res);
return res;
}
/**
* 高德api 根据地址获取经纬度
*
* @param name
* @return
*/
public static Map<String, String> getLatAndLogByName(String name) {
List<String> keyList = shuffle(keys);
if (CollectionUtils.isEmpty(keyList)) {
return new HashMap<>();
}
StringBuffer s = new StringBuffer();
int count = 0;
if (org.apache.commons.lang3.StringUtils.isNotBlank(name)) {
name = name.replaceAll(" ", "");
}
s.append("key=" + keyList.get(count) + "&keywords=" + name);
String res = sendGet("https://restapi.amap.com/v3/place/text", s.toString());
JSONObject jsonObject = JSONObject.parseObject(res);
JSONArray jsonArray = new JSONArray();
String info = jsonObject.getString("info");
if (!StringUtils.equals("OK", info)) {
for (int i = 0; i < keyList.size(); i++) {
count++;
if (count > keyList.size() - 1) {
return new HashMap<>();
} else {
StringBuffer s1 = new StringBuffer();
s1.append("key=" + keyList.get(count) + "&keywords=" + name);
res = sendGet("https://restapi.amap.com/v3/place/text", s1.toString());
jsonObject = JSONObject.parseObject(res);
info = jsonObject.getString("info");
if (StringUtils.equals("OK", info)) {
jsonArray = JSONArray.parseArray(jsonObject.getString("pois"));
break;
}
}
}
} else {
jsonArray = JSONArray.parseArray(jsonObject.getString("pois"));
}
if (jsonArray == null || jsonArray.size() == 0) {
return new HashMap<>();
} else {
JSONObject location = (JSONObject) jsonArray.get(0);
String add = location.get("location").toString();
String address = location.get("name").toString();
Map<String, String> data = new HashMap<>();
data.put("location", add);
data.put("address", address);
return data;
}
}
/**
* 高德api 根据地址获取经纬度
*
* @param name
* @return
*/
/*
* public static Map<String,String> getLatAndLogByName(String name) {
* StringBuffer s = new StringBuffer(); s.append("key=" + key + "&address=" +
* name); String res = sendPost("http://restapi.amap.com/v3/geocode/geo",
* s.toString()); log.info(res); JSONObject jsonObject =
* JSONObject.parseObject(res); JSONArray jsonArray =
* JSONArray.parseArray(jsonObject.getString("geocodes"));
* if(jsonArray.size()==0){ return new HashMap<>(); } else { JSONObject location
* = (JSONObject) jsonArray.get(0); String add =
* location.get("location").toString(); String address =
* location.get("formatted_address").toString(); Map<String,String> data = new
* HashMap<>(); data.put("location",add); data.put("address",address); return
* data; } }
*
* /** 高德api 根据地址获取经纬度
*
* @return
*/
public static String getAddByAMAP(String longitude, String latitude) {
StringBuffer sb1 = new StringBuffer();
sb1.append("key=").append(key).append("&location=").append(longitude).append(",").append(latitude);
String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", sb1.toString());
JSONObject jsonObject = JSONObject.parseObject(res);
JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.getString("regeocode"));
String add = jsonObject1.get("formatted_address").toString();
return add;
}
/**
* 高德api 坐标转换---转换至高德经纬度
*
* @return
*/
public static String convertLocations(String longitude, String latitude, String type) {
StringBuffer sb2 = new StringBuffer();
sb2.append("key=").append(key).append("&locations=").append(longitude).append(",").append(latitude)
.append("&coordsys=");
if (type == null) {
sb2.append("gps");
} else {
sb2.append(type);
}
String res = sendPost("http://restapi.amap.com/v3/assistant/coordinate/convert", sb2.toString());
JSONObject jsonObject = JSONObject.parseObject(res);
String add = jsonObject.get("locations").toString();
return add;
}
public static String getAddByName(String name) {
// log 大 lat 小
// 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/geocoding?a=" + name;
String res = "";
try {
URL url1 = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(res);
String longitude = jsonObject.getString("lon");
String latitude = jsonObject.getString("lat");
System.err.println(jsonObject);
res = getNearbyAdd(longitude, latitude);
} catch (Exception e) {
log.info("error in wapaction,and e is " + e.getMessage());
e.printStackTrace();
}
return res;
}
public static String getNearbyAdd(String longitude, String latitude) {
String add = sendGet("http://ditu.amap.com/service/regeo",
"longitude=" + longitude + "&latitude=" + latitude + "&type=010");
return add;
}
/**
* 高德api 关键字模糊查询
*
* @param keyWord
* @param city
* @return
*/
public static String getKeywordsAddByLbs(String keyWord, String city) {
StringBuffer sb3 = new StringBuffer();
sb3.append("key=" + key + "&keywords=");
if (keyWord.contains(" ")) {
String[] str = keyWord.split(" ");
for (int i = 0; i < str.length; i++) {
if (i == 0) {
sb3.append(str[i]);
} else {
sb3.append("+" + str[i]);
}
}
} else {
sb3.append(keyWord);
}
sb3.append("&city=" + city);
sb3.append("offset=10&page=1");
String around = sendPost("http://restapi.amap.com/v3/place/text", sb3.toString());
return around;
}
/**
* 高德api 经纬度/关键字 附近地标建筑及地点查询
*
* @param longitude
* @param latitude
* @param keyWord
* @return
*/
public static String getAroundAddByLbs(String longitude, String latitude, String keyWord) {
String around = sendPost("http://restapi.amap.com/v3/place/around", "key=" + key + "&location=" + longitude
+ "," + latitude + "&keywords=" + keyWord + "&radius=2000&offset=10&page=1");
return around;
}
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
// log.info(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* GET请求数据
*
* @param get_url url地址
* @param content key=value形式
* @return 返回结果
* @throws Exception
*/
public static String sendGetData(String get_url, String content) throws Exception {
String result = "";
URL getUrl = null;
BufferedReader reader = null;
String lines = "";
HttpURLConnection connection = null;
try {
if (content != null && !content.equals(""))
get_url = get_url + "?" + content;
// get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
getUrl = new URL(get_url);
connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
// 取得输入流,并使用Reader读取
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
while ((lines = reader.readLine()) != null) {
result = result + lines;
}
return result;
} catch (Exception e) {
throw e;
} finally {
if (reader != null) {
reader.close();
reader = null;
}
connection.disconnect();
}
}
/**
* @param POST_URL url地址
* @param content key=value形式
* @return 返回结果
* @throws Exception
*/
public static String sendPostData(String POST_URL, String content) throws Exception {
HttpURLConnection connection = null;
DataOutputStream out = null;
BufferedReader reader = null;
String line = "";
String result = "";
try {
URL postUrl = new URL(POST_URL);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
// Post 请求不能使用缓存
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
// content = URLEncoder.encode(content, "utf-8");
// DataOutputStream.writeBytes将字符串中的16位的unicode字符�?8位的字符形式写道流里�?
out.writeBytes(content);
out.flush();
out.close();
// 获取结果
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
while ((line = reader.readLine()) != null) {
result = result + line;
}
return result;
} catch (Exception e) {
throw e;
} finally {
if (out != null) {
out.close();
out = null;
}
if (reader != null) {
reader.close();
reader = null;
}
connection.disconnect();
}
}
/*
* 过滤掉html里不安全的标签,不允许用户输入这些标�?
*/
public static String htmlFilter(String inputString) {
// return inputString;
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
/*
* Pattern p_script; java.util.regex.Matcher m_script;
*/
try {
String regEx_script = "<[\\s]*?(script|style)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(script|style)[\\s]*?>";
String regEx_onevent = "on[^\\s]+=\\s*";
String regEx_hrefjs = "href=javascript:";
String regEx_iframe = "<[\\s]*?(iframe|frameset)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(iframe|frameset)"
+ "[\\s]*?>";
String regEx_link = "<[\\s]*?link[^>]*?/>";
htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr = Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr = Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr = Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr = Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;
}
private static List<String> shuffle(String[] arr) {
List<String> keyList = new ArrayList<>();
if (arr.length > 1) {
for (int i = 0; i < keys.length; i++) {
keyList.add(keys[i]);
}
Collections.shuffle(keyList);
}
return keyList;
}
/**
* 货车路径规划
*
* @param origins
* @param destination
* @return
*/
public static Map<String, Double> truckDirection(String origins, String destination, String size,String danoneKey) {
String urlString = "https://restapi.amap.com/v4/direction/truck";
StringBuilder params = new StringBuilder();
Map<String, Double> map = new HashMap<>();
params.append("origin=").append(origins).append("&destination=").append(destination).append("&strategy=10")
.append("&size=").append(size).append("&nosteps=1").append("&key=").append(danoneKey);
try {
String res = sendGet(urlString, params.toString());
JSONObject jsonObject = JSONObject.parseObject(res);
Integer status = (Integer) jsonObject.get("errcode");
if (status == 0) {
JSONObject data = (JSONObject) jsonObject.get("data");
JSONObject route = (JSONObject) data.get("route");
JSONArray paths = (JSONArray) route.get("paths");
JSONObject result = (JSONObject) paths.get(0);
Integer distance = (Integer) result.get("distance");
Integer duration = (Integer) result.get("duration");
map.put("distance", distance.doubleValue());
map.put("time", duration.doubleValue());
} else {
log.info("请求失败rul:{}", params.toString());
log.info("请求失败信息message:{}", res);
}
} catch (Exception e) {
log.info("error in wapaction,and e is " + e.getMessage());
}
return map;
}
public static void main(String[] args) {
Map<String, Double> map = truckDirection("107.921385,32.510652", "110.824882,39.135157", "2","");
if (org.apache.commons.collections4.MapUtils.isNotEmpty(map)) {
System.out.println("distacne:" + map.get("distance") / 1000);
System.out.println("time:" + map.get("time") / 3600);
} else {
}
}
}
MD5Utils MD5工具类
package com.yhl.ros.common.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;
/**
*
* @ClassName: MD5Utils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:19
*/
@Slf4j
public class MD5Utils {
public static String getMD5(String str) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
} catch (NoSuchAlgorithmException e) {
log.error("", e);
}
return new BigInteger(1, md == null ? null : md.digest()).toString(16);
}
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
// **********************************
/*
* 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的, 这里把它们实现成为static
* final是表示了只读,切能在同一个进程空间内的多个 Instance间共享
*/
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0 };
/*
* 下面的三个成员是MD5计算过程中用到的3个核心数据,在原始的C实现中 被定义到MD5_CTX结构中
*
*/
private long[] state = new long[4]; // state (ABCD)
private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb first)
private byte[] buffer = new byte[64]; // input buffer
/*
* digestHexStr是MD5的唯一一个公共成员,是最新一次计算结果的 16进制ASCII表示.
*/
public String digestHexStr;
/*
* digest,是最新一次计算结果的2进制内部表示,表示128bit的MD5值.
*/
private byte[] digest = new byte[16];
/*
* 类MD5最主要的公共方法,入口参数是你想要进行MD5变换的字符串 返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的.
*/
public String md5(String inbuf) {
md5Init();
md5Update(inbuf.getBytes(), inbuf.length());
md5Final();
digestHexStr = "";
for (int i = 0; i < 16; i++) {
digestHexStr += byteHEX(digest[i]);
}
// return digestHexStr.substring(8,24); //16位md5
return digestHexStr; // 32位md5
}
public MD5Utils() {
md5Init();
return;
}
/* md5Init是一个初始化函数,初始化核心变量,装入标准的幻数 */
private void md5Init() {
count[0] = 0L;
count[1] = 0L;
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
return;
}
/* F, G, H ,I 是4个基本的MD5函数, */
private long F(long x, long y, long z) {
return (x & y) | ((~x) & z);
}
private long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private long H(long x, long y, long z) {
return x ^ y ^ z;
}
private long I(long x, long y, long z) {
return y ^ (x | (~z));
}
/*
* FF,GG,HH和II将调用F,G,H,I进行近一步变换 FF, GG, HH, and II transformations for rounds 1,
* 2, 3, and 4. Rotation is separate from addition to prevent recomputation.
*/
private long FF(long a, long b, long c, long d, long x, long s, long ac) {
a += F(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long GG(long a, long b, long c, long d, long x, long s, long ac) {
a += G(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long HH(long a, long b, long c, long d, long x, long s, long ac) {
a += H(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long II(long a, long b, long c, long d, long x, long s, long ac) {
a += I(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
/*
* md5Update是MD5的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个
* 函数由md5调用,调用之前需要调用md5init,因此把它设计成private的
*/
private void md5Update(byte[] inbuf, int inputLen) {
int i, index, partLen;
byte[] block = new byte[64];
index = (int) (count[0] >>> 3) & 0x3F;
// /* Update number of bits */
long val = count[0] += (inputLen << 3);
if (val < (inputLen << 3))
count[1]++;
count[1] += (inputLen >>> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (inputLen >= partLen) {
md5Memcpy(buffer, inbuf, index, 0, partLen);
md5Transform(buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
md5Memcpy(block, inbuf, 0, i, 64);
md5Transform(block);
}
index = 0;
} else
i = 0;
/// * Buffer remaining input */
md5Memcpy(buffer, inbuf, index, i, inputLen - i);
}
/*
* md5Final整理和填写输出结果
*/
private void md5Final() {
byte[] bits = new byte[8];
int index, padLen;
/// * Save number of bits */
Encode(bits, count, 8);
/// * Pad out to 56 mod 64.
index = (int) (count[0] >>> 3) & 0x3f;
padLen = (index < 56) ? (56 - index) : (120 - index);
md5Update(PADDING, padLen);
/// * Append length (before padding) */
md5Update(bits, 8);
/// * Store state in digest */
Encode(digest, state, 16);
}
/*
* md5Memcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的 字节拷贝到output的outpos位置开始
*/
private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos, int len) {
int i;
for (i = 0; i < len; i++)
output[outpos + i] = input[inpos + i];
}
/*
* md5Transform是MD5核心变换程序,有md5Update调用,block是分块的原始字节
*/
private void md5Transform(byte block[]) {
long a = state[0], b = state[1], c = state[2], d = state[3];
long[] x = new long[16];
Decode(x, block, 64);
/* Round 1 */
a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
/*
* Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的,只拆低32bit
*/
private void Encode(byte[] output, long[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (byte) (input[i] & 0xffL);
output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);
output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);
output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);
}
}
/*
* Decode把byte数组按顺序合成成long数组,因为java的long类型是64bit的, 只合成低32bit,高32bit清零
*/
private void Decode(long[] output, byte[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8) | (b2iu(input[j + 2]) << 16)
| (b2iu(input[j + 3]) << 24);
return;
}
/*
* b2iu是一个把byte按照不考虑正负号的原则的"升位"程序,因为java没有unsigned运算
*/
public static long b2iu(byte b) {
return b < 0 ? b & 0x7F + 128 : b;
}
/*
* byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示, 因为java中的byte的toString无法实现这一点
*/
public static String byteHEX(byte ib) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char[] ob = new char[2];
ob[0] = Digit[(ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
public static String toMD5(String source) {
MD5Utils md5 = new MD5Utils();
return md5.md5(source);
}
}
MyBeanUtils MyBean工具类
package com.yhl.ros.common.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @ClassName: MyBeanUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-04-14 17:31
*/
public class MyBeanUtils {
public static Field findField(Class<?> clazz, String name) {
try {
return clazz.getField(name);
} catch (NoSuchFieldException ex) {
return findDeclaredField(clazz, name);
}
}
public static Field findDeclaredField(Class<?> clazz, String name) {
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException ex) {
if (clazz.getSuperclass() != null) {
return findDeclaredField(clazz.getSuperclass(), name);
}
return null;
}
}
public static Method findMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
return findDeclaredMethod(clazz, methodName, paramTypes);
}
}
public static Method findDeclaredMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
try {
return clazz.getDeclaredMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
if (clazz.getSuperclass() != null) {
return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes);
}
return null;
}
}
public static Object getProperty(Object obj, String name) throws NoSuchFieldException {
Object value = null;
Field field = findField(obj.getClass(), name);
if (field == null) {
throw new NoSuchFieldException("no such field [" + name + "]");
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
value = field.get(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
field.setAccessible(accessible);
return value;
}
public static void setProperty(Object obj, String name, Object value) throws NoSuchFieldException {
Field field = findField(obj.getClass(), name);
if (field == null) {
throw new NoSuchFieldException("no such field [" + name + "]");
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
field.set(obj, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
field.setAccessible(accessible);
}
public static Map<String, Object> obj2Map(Object obj, Map<String, Object> map) {
if (map == null) {
map = new HashMap<String, Object>();
}
if (obj != null) {
try {
Class<?> clazz = obj.getClass();
do {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod)) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
field.setAccessible(accessible);
}
clazz = clazz.getSuperclass();
} while (clazz != null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return map;
}
/**
* 获得父类集合,包含当前class
*
* @param clazz
* @return
*/
public static List<Class<?>> getSuperclassList(Class<?> clazz) {
List<Class<?>> clazzes = new ArrayList<Class<?>>(3);
clazzes.add(clazz);
clazz = clazz.getSuperclass();
while (clazz != null) {
clazzes.add(clazz);
clazz = clazz.getSuperclass();
}
return Collections.unmodifiableList(clazzes);
}
}
SerializeUtil 序列化工具类
package com.yhl.ros.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
*
* @ClassName: SerializeUtil
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:19
*/
public class SerializeUtil {
/**
* 序列化
*
* @param object
* @return
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
}
return null;
}
/**
* 反序列化
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
SFTPUtils sftp上传文件工具类
package com.yhl.ros.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
/**
*
* @ClassName: SFTPUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:20
*/
@Slf4j
public class SFTPUtils {
private static ChannelSftp sftp;
private static SFTPUtils instance = null;
private SFTPUtils() {
}
public static SFTPUtils getInstance(String host, int port, String username, String password) {
/*
* if (instance == null) { synchronized (SFTPUtils.class) { instance = new
* SFTPUtils(); sftp = instance.connect(host, port, username, password); //获取连接
* } }
*/
instance = new SFTPUtils();
sftp = instance.connect(host, port, username, password); // 获取连接
return instance;
}
public static void main(String[] args) {
SFTPUtils instance = getInstance("10.7.100.17", 22, "youhl", "youhl");
instance.upload("/home/youhl/FTP_File/RouteFee/active", "C:/Users/xianh/Desktop/shuhai_test_order_valid_no.sql");
}
/**
* 连接sftp服务器
*
* @param host
* 主机
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
log.info("SFTP Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
log.info("Connected to " + host);
} catch (Exception e) {
log.error(e.getMessage());
}
return sftp;
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param uploadFile
* 要上传的文件
*/
public boolean upload(String directory, String uploadFile) {
try {
createDir(directory, sftp);
sftp.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
public void createDir(String createpath, ChannelSftp sftp) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
return;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
sftp.cd(createpath);
} catch (SftpException e) {
throw new RuntimeException("创建路径错误:" + createpath);
}
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param file
* 要上传的文件
*/
public boolean upload(String directory, InputStream inputStream, String fileName) {
try {
if (inputStream == null) {
return false;
}
createDir(directory, sftp);
sftp.cd(directory);
sftp.put(inputStream, fileName);
inputStream.close();
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
*/
public File download(String directory, String downloadFile, String saveFile) {
try {
sftp.cd(directory);
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFile, fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
*
* @param directory 文件所在目录
* @param downloadFile 需要下载的文件
* @return
*/
public InputStream getFromSFTP(String directory, String downloadFile) {
try {
sftp.cd(directory);
InputStream inputStream = sftp.get(downloadFile);
return inputStream;
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* 下载文件
*
* @param downloadFilePath
* 下载的文件完整目录
* @param saveFile
* 存在本地的路径
*/
public File download(String downloadFilePath, String saveFile) {
try {
int i = downloadFilePath.lastIndexOf('/');
if (i == -1)
return null;
sftp.cd(downloadFilePath.substring(0, i));
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
*/
public void delete(String directory, String deleteFile) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
log.error(e.getMessage());
}
}
public void disconnect() {
try {
sftp.getSession().disconnect();
} catch (JSchException e) {
log.error("JSchException", e);
}
// sftp.quit();
sftp.disconnect();
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @throws SftpException
*/
@SuppressWarnings("unchecked")
public Vector<LsEntry> listFiles(String directory) {
Vector<LsEntry> result = new Vector<LsEntry>();
try {
result = sftp.ls(directory);
} catch (SftpException e) {
// log.error("list files exception: {}", e);
}
return result;
}
}
StringUtils 字符串工具类
underscoreName 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。 例如:HelloWorld->HELLO_WORLD
camelName 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。例如:HELLO_WORLD->helloWorld
castTime 数字转化为至少保留两位的格式 例:5->05
dowWithComma 将字符串每个字节用逗号分割输出 例:1,2,3,4,5,->1,2,3,4,5 12345,->1,2,3,4,5
String.join(“,”,List) 把集合中的String用逗号拼接输出
package com.yhl.ros.common.utils;
import java.util.ArrayList;
import java.util.List;
/**
*
* @ClassName: StringUtils
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:21
*/
public class StringUtils {
/**
* 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br>
* 例如:HelloWorld->HELLO_WORLD
*
* @param name
* 转换前的驼峰式命名的字符串
* @return 转换后下划线大写方式命名的字符串
*/
public static String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
// 将第一个字符处理成大写
result.append(name.substring(0, 1).toUpperCase());
// 循环处理其余字符
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
// 在大写字母前添加下划线
if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
result.append("_");
}
// 其他字符直接转成大写
result.append(s.toUpperCase());
}
}
return result.toString();
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
* 例如:HELLO_WORLD->helloWorld
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String camelName(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
} else if (!name.contains("_")) {
// 不含下划线,直接转小写
return name.toLowerCase();
}
// 用下划线将原始字符串分割
String camels[] = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue;
}
// 处理真正的驼峰片段
if (result.length() == 0) {
// 第一个驼峰片段,全部字母都小写
result.append(camel.toLowerCase());
} else {
// 其他的驼峰片段,首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
}
return result.toString();
}
public static String dowWithComma(String dowString) {
if (org.apache.commons.lang3.StringUtils.isNoneBlank(dowString)) {
char[] charArray = dowString.replaceAll(",", "").toCharArray();
List<String> temp = new ArrayList<>();
for (char c : charArray) {
temp.add(String.valueOf(c));
}
String join = String.join(",", temp);
return join;
}
return dowString;
}
public static String castTime(int number) {
return String.format("%02d", number);
}
}
ZipFilesUtil 压缩文件工具类
package com.yhl.ros.common.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: ZipFilesUtil
* @Package: com.yhl.ros.common.utils
* @Description: 描述
* @Date: 2020-02-12 01:21
*/
@Slf4j
public class ZipFilesUtil {
public static void compress(File f, String baseDir, ZipOutputStream zos) {
if (!f.exists()) {
log.warn("待压缩的文件目录或文件" + f.getName() + "不存在");
return;
}
File[] fs = f.listFiles();
BufferedInputStream bis = null;
// ZipOutputStream zos = null;
byte[] bufs = new byte[1024 * 10];
FileInputStream fis = null;
try {
// zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i < fs.length; i++) {
String fName = fs[i].getName();
log.warn("压缩:" + baseDir + fName);
if (fs[i].isFile()) {
ZipEntry zipEntry = new ZipEntry(baseDir + fName);//
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(fs[i]);
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
// 如果需要删除源文件,则需要执行下面2句
// fis.close();
// fs[i].delete();
} else if (fs[i].isDirectory()) {
compress(fs[i], baseDir + fName + "/", zos);
}
} // end for
} catch (IOException e) {
log.error("", e);
} finally {
// 关闭流
try {
if (null != bis) {
bis.close();
}
// if(null!=zos)
// zos.close();
if (null != fis) {
fis.close();
}
} catch (IOException e) {
log.error("", e);
}
}
}
}