700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JAVA 工具类大集合

JAVA 工具类大集合

时间:2021-11-17 20:51:55

相关推荐

JAVA 工具类大集合

身份证号码验证、正则表达式大全、常用日期工具类、图片高报真缩放工具类、文件类工具类

1、身份证号码验证

package xxx;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Random;/*** 身份证验证的工具(支持15位或18位省份证)* 身份证号码结构:* <p>* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。* 排列顺序从左至右依次为:6位数字地址码,8位数字出生日期码,3位数字顺序码和1位数字校验码。* <p>* 地址码(前6位):表示对象常住户口所在县(市、镇、区)的行政区划代码,按GB/T2260的规定执行。* <li>前1、2位数字表示:所在省份的代码;</li>* <li>第3、4位数字表示:所在城市的代码;</li>* <li>第5、6位数字表示:所在区县的代码;</li>* <p>* 出生日期码,(第7位 - 14位):表示编码对象出生年、月、日,按GB按GB/T7408的规定执行,年、月、日代码之间不用分隔符。* <p>* 顺序码(第15位至17位):表示在同一地址码所标示的区域范围内,对同年、同月、同日出生的人编订的顺序号,顺序码的奇数分配给男性,偶数分配给女性。* <li>第15、16位数字表示:所在地的派出所的代码;</li>* <li>第17位数字表示性别:奇数表示男性,偶数表示女性;</li>* <li>第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。</li>* <p>* 校验码(第18位数):* <p>* 十七位数字本体码加权求和公式 s = sum(Ai*Wi), i = 0..16,先对前17位数字的权求和;* Ai:表示第i位置上的身份证号码数字值.Wi:表示第i位置上的加权因子.Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2;* 计算模 Y = mod(S, 11)* 通过模得到对应的模 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2* <p>* 计算步骤:* 1.将前17位数分别乘以不同的系数。从第1位到第17位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2* 2.将这17位数字和系数相乘的结果相加。* 3.用加出来和除以11,看余数是多少* 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字,分别对应的最后一位身份证的号码为:1 0 X 9 8 7 6 5 4 3* <p>*/public class IDCardUtil{/*** <pre>* 省、直辖市代码表:*11 : 北京 12 : 天津 13 : 河北 14 : 山西 15 : 内蒙古*21 : 辽宁 22 : 吉林 23 : 黑龙江 31 : 上海 32 : 江苏*33 : 浙江 34 : 安徽 35 : 福建 36 : 江西 37 : 山东*41 : 河南 42 : 湖北 43 : 湖南 44 : 广东 45 : 广西 46 : 海南*50 : 重庆 51 : 四川 52 : 贵州 53 : 云南 54 : 西藏*61 : 陕西 62 : 甘肃 63 : 青海 64 : 宁夏 65 : 新疆*71 : 台湾*81 : 香港 82 : 澳门*91 : 国外* </pre>*/final static String CITY_CODE[] = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"};/*** 效验码*/final static char[] PARITYBIT = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};/*** 加权因子* Math.pow(2, i - 1) % 11*/final static int[] POWER = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};/*** 身份证验证** @param id 号码内容* @return 是否有效*/public final static boolean isValid(String id){if (id == null)return false;int len = id.length();if (len != 15 && len != 18)return false;//校验区位码if (!validCityCode(id.substring(0, 2)))return false;//校验生日if (!validDate(id))return false;if (len == 15)return true;//校验位数return validParityBit(id);}private static boolean validParityBit(String id){char[] cs = id.toUpperCase().toCharArray();int power = 0;for (int i = 0; i < cs.length; i++){//最后一位可以是Xif (i == cs.length - 1 && cs[i] == 'X')break;// 非数字if (cs[i] < '0' || cs[i] > '9')return false;// 加权求和if (i < cs.length - 1){power += (cs[i] - '0') * POWER[i];}}return PARITYBIT[power % 11] == cs[cs.length - 1];}private static boolean validDate(String id){try{String birth = id.length() == 15 ? "19" + id.substring(6, 12) : id.substring(6, 14);SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");Date birthDate = sdf.parse(birth);if (!birth.equals(sdf.format(birthDate)))return false;}catch (ParseException e){return false;}return true;}private static boolean validCityCode(String cityCode){for (String code : CITY_CODE){if (code.equals(cityCode))return true;}return false;}/*** 将15位的身份证转成18位身份证** @param id* @return*/final public static String id15To18(String id){if (id == null || id.length() != 15)return null;if (!isValid(id))return null;String id17 = id.substring(0, 6) + "19" + id.substring(6);int power = 0;char[] cs = id17.toCharArray();for (int i = 0; i < cs.length; i++){power += (cs[i] - '0') * POWER[i];}// 将前17位与第18位校验码拼接return id17 + String.valueOf(PARITYBIT[power % 11]);}/*** 生成随机整数* <p>** @param min* @param max* @return*/public static int rand(int min, int max){Random random = new Random();return random.nextInt(max + 1) % (max - min + 1) + min;}public final static String generateID(){// 地址码String body = CITY_CODE[rand(0, CITY_CODE.length - 1)] + "0101";// 出生年String y = String.valueOf(rand(1950, Calendar.getInstance().get(Calendar.YEAR)));String m = String.valueOf(rand(1, 12));if (m.length() == 1)m = "0" + m;String d = String.valueOf(rand(1, 28));if (d.length() == 1)d = "0" + d;String idx = String.valueOf(rand(1, 999));if (idx.length() == 1)idx = "00" + idx;else if (idx.length() == 2)idx = "0" + idx;body += y + m + d + idx;// 累加body部分与位置加权的积int power = 0;char[] cs = body.toCharArray();for (int i = 0; i < cs.length; i++){power += (cs[i] - '0') * POWER[i];}// 得出校验码return body + String.valueOf(PARITYBIT[power % 11]);}}

2、正则表达式大全

package xxxxx;import mons.lang.StringUtils;public class ValidUtils {private static final String mobile = "^(13|15|18|17|16)[0-9]{9}$";private static final String codeAndMobile = "^\\+[0-9]{2}\\-(13|15|18|17|16)[0-9]{9}$";/**整数*/private static final String intege="^-?[1-9]\\d*$"; /** 正整数*/private static final String intege1="^[1-9]\\d*$"; /** 负整数*/private static final String intege2="^-[1-9]\\d*$";/** 数字*/private static final String num="^([+-]?)\\d*\\.?\\d+$"; /** 正数(正整数 + 0)*/private static final String num1="^[1-9]\\d*|0$"; /** 负数(负整数 + 0)*/private static final String num2="^-[1-9]\\d*|0$"; /** 浮点数*/private static final String decmal="^([+-]?)\\d*\\.\\d+$"; /** 正浮点数*/private static final String decmal1="^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$"; /** 负浮点数*/private static final String decmal2="^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$";/** 浮点数*/private static final String decmal3="^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$"; /** 非负浮点数(正浮点数 + 0)*/private static final String decmal4="^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$"; /**非正浮点数(负浮点数 + 0) */private static final String decmal5="^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$";/** 邮件*/private static final String email="^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"; /** 颜色*/private static final String color="^[a-fA-F0-9]{6}$"; /** url*/private static final String url="^http[s]?=\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$"; /** 仅中文*/private static final String chinese="^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$"; /** 仅ACSII字符*/private static final String ascii="^[\\x00-\\xFF]+$"; /**邮编 */private static final String zipcode="^\\d{6}$"; /** ip地址*/private static final String ip4="^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$"; /** 非空*/private static final String notempty="^\\S+$"; /**图片 */private static final String picture="(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$"; /** 压缩文件*/private static final String rar="(.*)\\.(rar|zip|7zip|tgz)$";/** 日期*/private static final String date="^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$"; /** QQ号码*/private static final String qq="^[1-9]*[1-9][0-9]*$"; /** 电话号码的函数(包括验证国内区号;国际区号;分机号)*/private static final String tel="^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{1,}))?$"; /** 用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串*/private static final String username="^\\w+$"; /** 字母*/private static final String letter="^[A-Za-z]+$"; private static final String letterAndSpace="^[A-Za-z ]+$"; /** 大写字母*/private static final String letter_u="^[A-Z]+$"; /** 小写字母*/private static final String letter_l="^[a-z]+$"; /** 身份证*/private static final String idcard="^[1-9]([0-9]{14}|[0-9]{17})$"; /**判断字符串是否为浮点数*/private static final String isFloat="^[-]?\\d+(\\.\\d+)?$";/**判断字符串是否为正浮点数*/private static final String isUFloat="^\\d+(\\.\\d+)?$";/**判断是否是整数*/private static final String isInteger="^[-]?\\d+$";/**判断是否是正整数*/private static final String isUInteger="^\\d+$";/**判断车辆Vin码*/private static final String isCarVin="^[1234567890WERTYUPASDFGHJKLZXCVBNM]{13}[0-9]{4}$";/** 手机号 */public static boolean isMobile(String input){return matches(mobile, input);}public static boolean isCodeAndMobile(String input){return matches(codeAndMobile, input);}/** 整数 */public static boolean isIntege(String input){return matches(intege, input);}/** 正整数 */public static boolean isintege1(String input){return matches(intege1, input);}/** 负整数*/public static boolean isIntege2(String input){return matches(intege2, input);}/** 数字 */public static boolean isNum(String input){return matches(num, input);}/** 正数(正整数 + 0) */public static boolean isNum1(String input){return matches(num1, input);}/** 负数(负整数 + 0)*/public static boolean isNum2(String input){return matches(num2, input);}/** 浮点数*/public static boolean isDecmal(String input){return matches(decmal, input);}/** 正浮点数*/public static boolean isDecmal1(String input){return matches(decmal1, input);}/** 负浮点数*/public static boolean isDecmal2(String input){return matches(decmal2, input);}/**浮点数 */public static boolean isDecmal3(String input){return matches(decmal3, input);}/** 非负浮点数(正浮点数 + 0)*/public static boolean isDecmal4(String input){return matches(decmal4, input);}/** 非正浮点数(负浮点数 + 0)*/public static boolean isDecmal5(String input){return matches(decmal5, input);}/** 邮件*/public static boolean isEmail(String input){return matches(email, input);}/** 颜色*/public static boolean isColor(String input){return matches(color, input);}/** url*/public static boolean isUrl(String input){return matches(url, input);}/** 中文*/public static boolean isChinese(String input){return matches(chinese, input);}/** ascii码*/public static boolean isAscii(String input){return matches(ascii, input);}/** 邮编*/public static boolean isZipcode(String input){return matches(zipcode, input);}/** IP地址*/public static boolean isIP4(String input){return matches(ip4, input);}/** 非空*/public static boolean isNotEmpty(String input){return matches(notempty, input);}/** 图片*/public static boolean isPicture(String input){return matches(picture, input);}/** 压缩文件*/public static boolean isRar(String input){return matches(rar, input);}/** 日期*/public static boolean isDate(String input){return matches(date, input);}/** qq*/public static boolean isQQ(String input){return matches(qq, input);}/** 电话号码的函数(包括验证国内区号;国际区号;分机号)*/public static boolean isTel(String input){return matches(tel, input);}/** 用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串*/public static boolean isUserName(String input){return matches(username, input);}/**字母*/public static boolean isLetter(String input){return matches(letter, input);}public static boolean isLetterAndSpace(String input){return matches(letterAndSpace, input);}/** 小写字母*/public static boolean isLowLetter(String input){return matches(letter_l, input);}/** 大写字母*/public static boolean isUpperLetter(String input){return matches(letter_u, input);}/** 身份证*/public static boolean isIDCard(String input){return matches(idcard, input);}public static boolean isFloat(String input){return matches(isFloat, input);}public static boolean isUFloat(String input){return matches(isUFloat, input);}public static boolean isInteger(String input){return matches(isInteger, input);}public static boolean isUInteger(String input){return matches(isUInteger, input);}public static boolean isCarVin(String carVin){return matches(isCarVin, carVin);}public static boolean matches(String regex,String input){if(StringUtils.isBlank(input)) return false;if(input.matches(regex))return true;return false;}public static void main(String[] args) {/*System.out.println(isInteger("1"));System.out.println(isInteger("0"));System.out.println(isInteger("-1"));System.out.println(isInteger("1.0"));System.out.println("--------------------");System.out.println(isUInteger("-1"));System.out.println(isUInteger("0"));System.out.println(isUInteger("10"));System.out.println(isUInteger("1.3"));*/System.out.println(isLetterAndSpace("tai wan"));}}

3、常用日期工具类

package xxxxx;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.regex.Pattern;public class DateUtil {private static final int[] DAY_OF_MONTH = new int[] { 31, 28, 31, 30, 31,30, 31, 31, 30, 31, 30, 31 };/*** * @param strDate* 输入日期* @param dayNum* 相隔天数 正整数表示前推 ,负整数表示后推* @return 日期字符串* @throws ParseException*/public static String getDifferDate(String strDate, int dayNum)throws ParseException {SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");Date date = sf.parse(strDate);Calendar c = Calendar.getInstance();c.setTime(date);c.add(Calendar.DATE, dayNum);String sqldate = sf.format(c.getTime());return sqldate;}/*** 取得当前日期相隔dayNum天的日期* * @param strDate* @param dayNum* @return* @throws ParseException*/public static String getDifferDate(int dayNum) throws ParseException {Date date = new Date();SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");Calendar c = Calendar.getInstance();c.setTime(date);c.add(Calendar.DATE, dayNum);String strDate = sf.format(c.getTime());return strDate;}/*** 把日期字符串转换为util.date类型* * @param strDate* 日期字符串(yyyy-MM-dd)* * * @return java.sql.date 类型*/public static java.util.Date getDate(String strDate) {return java.sql.Date.valueOf(strDate);}/*** 校验日期YYYY-MM-DD格式是否正确* * @param date* @return*/public static boolean checkDateForm(String date) {if (date == null || "".equals(date))return false;String eL = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";return pile(eL).matcher(date).matches();}/*** 取得指定天数后的时间* * @param date* 基准时间* @param dayAmount* 指定天数,允许为负数* @return 指定天数后的时间*/public static Date addDay(Date date, int dayAmount) {if (date == null) {return null;}Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.DATE, dayAmount);return calendar.getTime();}/*** 取得指定小时数后的时间* * @param date* 基准时间* @param hourAmount* 指定小时数,允许为负数* @return 指定小时数后的时间*/public static Date addHour(Date date, int hourAmount) {if (date == null) {return null;}Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.HOUR, hourAmount);return calendar.getTime();}/*** 取得指定分钟数后的时间* * @param date* 基准时间* @param minuteAmount* 指定分钟数,允许为负数* @return 指定分钟数后的时间*/public static Date addMinute(Date date, int minuteAmount) {if (date == null) {return null;}Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.MINUTE, minuteAmount);return calendar.getTime();}/*** 比较两日期对象中的小时和分钟部分的大小.* * @param date* 日期对象1, 如果为 <code>null</code> 会以当前时间的日期对象代替* @param anotherDate* 日期对象2, 如果为 <code>null</code> 会以当前时间的日期对象代替* @return 如果日期对象1大于日期对象2, 则返回大于0的数; 反之返回小于0的数; 如果两日期对象相等, 则返回0.*/public static int compareHourAndMinute(Date date, Date anotherDate) {if (date == null) {date = new Date();}if (anotherDate == null) {anotherDate = new Date();}Calendar cal = Calendar.getInstance();cal.setTime(date);int hourOfDay1 = cal.get(Calendar.HOUR_OF_DAY);int minute1 = cal.get(Calendar.MINUTE);cal.setTime(anotherDate);int hourOfDay2 = cal.get(Calendar.HOUR_OF_DAY);int minute2 = cal.get(Calendar.MINUTE);if (hourOfDay1 > hourOfDay2) {return 1;} else if (hourOfDay1 == hourOfDay2) {// 小时相等就比较分钟return minute1 > minute2 ? 1 : (minute1 == minute2 ? 0 : -1);} else {return -1;}}/*** 比较两日期对象的大小, 忽略秒, 只精确到分钟.* * @param date* 日期对象1, 如果为 <code>null</code> 会以当前时间的日期对象代替* @param anotherDate* 日期对象2, 如果为 <code>null</code> 会以当前时间的日期对象代替* @return 如果日期对象1大于日期对象2, 则返回大于0的数; 反之返回小于0的数; 如果两日期对象相等, 则返回0.*/public static int compareIgnoreSecond(Date date, Date anotherDate) {if (date == null) {date = new Date();}if (anotherDate == null) {anotherDate = new Date();}Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MILLISECOND, 0);date = cal.getTime();cal.setTime(anotherDate);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MILLISECOND, 0);anotherDate = cal.getTime();return pareTo(anotherDate);}/*** 取得当前时间的字符串表示,格式为-01-10 20:56:30.756* * @return 当前时间的字符串表示*/public static String currentDate2String() {return date2String(new Date());}/*** 取得当前时间的字符串表示,格式为-01-10* * @return 当前时间的字符串表示*/public static String currentDate2StringByDay() {return date2StringByDay(new Date());}/*** 取得今天的最后一个时刻* * @return 今天的最后一个时刻*/public static Date currentEndDate() {return getEndDate(new Date());}/*** 取得今天的第一个时刻* * @return 今天的第一个时刻*/public static Date currentStartDate() {return getStartDate(new Date());}/*** 把时间转换成字符串,格式为-01-10 20:56:30.756* * @param date* 时间* @return 时间字符串*/public static String date2String(Date date) {return date2String(date, "yyyy-MM-dd HH:mm:ss.SSS");}/*** 按照指定格式把时间转换成字符串,格式的写法类似yyyy-MM-dd HH:mm:ss.SSS* * @param date* 时间* @param pattern* 格式* @return 时间字符串*/public static String date2String(Date date, String pattern) {if (date == null) {return null;}return (new SimpleDateFormat(pattern)).format(date);}/*** 把时间转换成字符串,格式为-01-10* * @param date* 时间* @return 时间字符串*/public static String date2StringByDay(Date date) {return date2String(date, "yyyy-MM-dd");}/*** 把时间转换成字符串,格式为-01-10 20:56* * @param date* 时间* @return 时间字符串*/public static String date2StringByMinute(Date date) {return date2String(date, "yyyy-MM-dd HH:mm");}/*** 把时间转换成字符串,格式为-01-10 20:56:30* * @param date* 时间* @return 时间字符串*/public static String date2StringBySecond(Date date) {return date2String(date, "yyyy-MM-dd HH:mm:ss");}/*** 根据某星期几的英文名称来获取该星期几的中文数. <br>* e.g. <li>monday -> 一</li> <li>sunday -> 日</li>* * @param englishWeekName* 星期的英文名称* @return 星期的中文数*/public static String getChineseWeekNumber(String englishWeekName) {if ("monday".equalsIgnoreCase(englishWeekName)) {return "一";}if ("tuesday".equalsIgnoreCase(englishWeekName)) {return "二";}if ("wednesday".equalsIgnoreCase(englishWeekName)) {return "三";}if ("thursday".equalsIgnoreCase(englishWeekName)) {return "四";}if ("friday".equalsIgnoreCase(englishWeekName)) {return "五";}if ("saturday".equalsIgnoreCase(englishWeekName)) {return "六";}if ("sunday".equalsIgnoreCase(englishWeekName)) {return "日";}return null;}/*** 根据指定的年, 月, 日等参数获取日期对象.* * @param year* 年* @param month* 月* @param date* 日* @return 对应的日期对象*/public static Date getDate(int year, int month, int date) {return getDate(year, month, date, 0, 0);}/*** 根据指定的年, 月, 日, 时, 分等参数获取日期对象.* * @param year* 年* @param month* 月* @param date* 日* @param hourOfDay* 时(24小时制)* @param minute* 分* @return 对应的日期对象*/public static Date getDate(int year, int month, int date, int hourOfDay,int minute) {return getDate(year, month, date, hourOfDay, minute, 0);}/*** 根据指定的年, 月, 日, 时, 分, 秒等参数获取日期对象.* * @param year* 年* @param month* 月* @param date* 日* @param hourOfDay* 时(24小时制)* @param minute* 分* @param second* 秒* @return 对应的日期对象*/public static Date getDate(int year, int month, int date, int hourOfDay,int minute, int second) {Calendar cal = Calendar.getInstance();cal.set(year, month - 1, date, hourOfDay, minute, second);cal.set(Calendar.MILLISECOND, 0);return cal.getTime();}/*** 取得某个日期是星期几,星期日是1,依此类推* * @param date* 日期* @return 星期几*/public static int getDayOfWeek(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.DAY_OF_WEEK);}/*** 获取某天的结束时间, e.g. -10-01 23:59:59.999* * @param date* 日期对象* @return 该天的结束时间*/public static Date getEndDate(Date date) {if (date == null) {return null;}Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.HOUR_OF_DAY, 23);cal.set(Calendar.MINUTE, 59);cal.set(Calendar.SECOND, 59);cal.set(Calendar.MILLISECOND, 999);return cal.getTime();}/*** 取得一个月最多的天数* * @param year* 年份* @param month* 月份,0表示1月,依此类推* @return 最多的天数*/public static int getMaxDayOfMonth(int year, int month) {if (month == 1 && isLeapYear(year)) {return 29;}return DAY_OF_MONTH[month];}/*** 得到指定日期的下一天* * @param date* 日期对象* @return 同一时间的下一天的日期对象*/public static Date getNextDay(Date date) {return addDay(date, 1);}/*** 获取某天的起始时间, e.g. -10-01 00:00:00.000* * @param date* 日期对象* @return 该天的起始时间*/public static Date getStartDate(Date date) {if (date == null) {return null;}Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.HOUR_OF_DAY, 0);cal.set(Calendar.MINUTE, 0);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MILLISECOND, 0);return cal.getTime();}/*** 根据日期对象来获取日期中的时间(HH:mm:ss).* * @param date* 日期对象* @return 时间字符串, 格式为: HH:mm:ss*/public static String getTime(Date date) {if (date == null) {return null;}SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");return format.format(date);}/*** 根据日期对象来获取日期中的时间(HH:mm).* * @param date* 日期对象* @return 时间字符串, 格式为: HH:mm*/public static String getTimeIgnoreSecond(Date date) {if (date == null) {return null;}SimpleDateFormat format = new SimpleDateFormat("HH:mm");return format.format(date);}/*** 判断是否是闰年* * @param year* 年份* @return 是true,否则false*/public static boolean isLeapYear(int year) {Calendar calendar = Calendar.getInstance();return ((GregorianCalendar) calendar).isLeapYear(year);}/*** 取得一年中的第几周。* * @param date* @return*/public static int getWeekOfYear(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.WEEK_OF_YEAR);}/*** 获取上周的指定星期的日期。* * @param dayOfWeek* 星期几,取值范围是 {@link Calendar#MONDAY} - {@link Calendar#SUNDAY}*/public static Date getDateOfPreviousWeek(int dayOfWeek) {if (dayOfWeek > 7 || dayOfWeek < 1) {throw new IllegalArgumentException("参数必须是1-7之间的数字");}return getDateOfRange(dayOfWeek, -7);}/*** 获取本周的指定星期的日期。* * @param dayOfWeek* 星期几,取值范围是 {@link Calendar#MONDAY} - {@link Calendar#SUNDAY}*/public static Date getDateOfCurrentWeek(int dayOfWeek) {if (dayOfWeek > 7 || dayOfWeek < 1) {throw new IllegalArgumentException("参数必须是1-7之间的数字");}return getDateOfRange(dayOfWeek, 0);}/*** 获取下周的指定星期的日期。* * @param dayOfWeek* 星期几,取值范围是 {@link Calendar#MONDAY} - {@link Calendar#SUNDAY}*/public static Date getDateOfNextWeek(int dayOfWeek) {if (dayOfWeek > 7 || dayOfWeek < 1) {throw new IllegalArgumentException("参数必须是1-7之间的数字");}return getDateOfRange(dayOfWeek, 7);}private static Date getDateOfRange(int dayOfWeek, int dayOfRange) {Calendar cal = Calendar.getInstance();cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);cal.set(Calendar.DATE, cal.get(Calendar.DATE) + dayOfRange);cal.set(Calendar.HOUR_OF_DAY, 0);cal.set(Calendar.MINUTE, 0);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MILLISECOND, 0);return cal.getTime();}public static void main(String[] args) {// Date date =DateUtil.getDate("-01-17");// Date date = new Date();SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println(sf.format(new Date()));}}

4、图片高报真缩放工具类

package xxxx;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class NarrowImage {/*** @param im* 原始图像* @param resizeTimes* 倍数,比如0.5就是缩小一半,0.98等等double类型* @return 返回处理后的图像*/public BufferedImage zoomImage(String src) {BufferedImage result = null;try {File srcfile = new File(src);if (!srcfile.exists()) {System.out.println("文件不存在");}BufferedImage im = ImageIO.read(srcfile);/* 原始图像的宽度和高度 */int width = im.getWidth();int height = im.getHeight();// 压缩计算float resizeTimes = 0.3f; /* 这个参数是要转化成的倍数,如果是1就是转化成1倍 *//* 调整后的图片的宽度和高度 */int toWidth = (int) (width * resizeTimes);int toHeight = (int) (height * resizeTimes);/* 新生成结果图片 */result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0,null);} catch (Exception e) {System.out.println("创建缩略图发生异常" + e.getMessage());}return result;}public boolean writeHighQuality(BufferedImage im, String fileFullPath) {try {/* 输出到文件流 */FileOutputStream newimage = new FileOutputStream(fileFullPath);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);/* 压缩质量 */jep.setQuality(0.9f, true);encoder.encode(im, jep);/* 近JPEG编码 */newimage.close();return true;} catch (Exception e) {return false;} finally {// 压缩完毕后,删除原文件File file = new File(fileFullPath);// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除if (file.exists() && file.isFile()) {if (file.delete()) {System.out.println("删除文件" + fileFullPath + "成功!");} else {System.out.println("删除文件" + fileFullPath + "失败!");}} else {System.out.println("删除文件失败:" + fileFullPath + "不存在!");}}}/*** 测试图片压缩* * @param args*/public static void main(String[] args) {String inputFoler = "C:\\Users\\PC\\Desktop\\bcfb1f83-ee77-4e82-bf2f-48905b1089b1.jpg";/* 这儿填写你存放要缩小图片的文件夹全地址 */String outputFolder = "C:\\Users\\PC\\Desktop\\T-bcfb1f83-ee77-4e82-bf2f-48905b1089b1.jpg";/* 这儿填写你转化后的图片存放的文件夹 */NarrowImage narrowImage = new NarrowImage();narrowImage.writeHighQuality(narrowImage.zoomImage(inputFoler), outputFolder);}}

5、文件类工具类

package xxxx;import org.springframework.util.Assert;import java.io.*;import java.math.BigDecimal;import java.util.LinkedList;import java.util.Properties;/*** 文件操作工具类**/public final class FileUtil {/*** @param path path* @return p* @throws IOException io* @author jiangzeyin*/public static Properties getProperties(String path) throws IOException {Properties prop = new Properties();InputStream in = new FileInputStream(path);prop.load(in);return prop;}/*** 格式化单位** @param size size* @return str*/public static String getFormatSize(long size) {double kiloByte = size / 1024;if (kiloByte < 1) {return size + "Byte";}double megaByte = kiloByte / 1024;if (megaByte < 1) {BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";}double gigaByte = megaByte / 1024;if (gigaByte < 1) {BigDecimal result2 = new BigDecimal(Double.toString(megaByte));return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";}double teraBytes = gigaByte / 1024;if (teraBytes < 1) {BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";}BigDecimal result4 = new BigDecimal(teraBytes);return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";}/*** 判断文件是否存在** @param path path* @return boolean*/public static boolean exists(String path) {File f = new File(path);return f.exists();}/*** 创建文件路径** @param path path* @return boolean* @author jiangzeyin*/public static boolean mkdirs(String path) {return mkdirs(new File(path), path.endsWith("/"));}/*** @param file file* @param isPath isPath* @return boolean* @author jiangzeyin*/public static boolean mkdirs(File file, boolean isPath) {if (file == null)return false;if (isPath)return file.mkdirs();elsereturn file.getParentFile().mkdirs();}public static boolean mkdirs(File file) {return mkdirs(file, false);}/*** 读取文件全部内容** @param filefile* @param encoding encoding* @return str* @throws IOException io*/public static String readToString(File file, String encoding) throws IOException {BufferedReader br;StringBuffer stringBuffer = null;br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));String line = null;stringBuffer = new StringBuffer();while ((line = br.readLine()) != null) {stringBuffer.append(line);}br.close();return stringBuffer.toString();// 返回文件内容,默认编码}public static String readToString(File file) throws IOException {return readToString(file, "UTF-8");}public static String getFileEncode(String path) throws IOException {String charset = "asci";byte[] first3Bytes = new byte[3];boolean checked = false;BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));bis.mark(0);int read = bis.read(first3Bytes, 0, 3);if (read == -1)return charset;if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {charset = "Unicode";// UTF-16LEchecked = true;} else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {charset = "Unicode";// UTF-16BEchecked = true;} else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) {charset = "UTF8";checked = true;}bis.reset();if (!checked) {while ((read = bis.read()) != -1) {if (read >= 0xF0)break;if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBKbreak;if (0xC0 <= read && read <= 0xDF) {read = bis.read();if (0x80 <= read && read <= 0xBF)// 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB编码内continue;elsebreak;} else if (0xE0 <= read && read <= 0xEF) { // 也有可能出错,但是几率较小read = bis.read();if (0x80 <= read && read <= 0xBF) {read = bis.read();if (0x80 <= read && read <= 0xBF) {charset = "UTF-8";break;} elsebreak;} elsebreak;}}// TextLogger.getLogger().info(loc + " " +// Integer.toHexString(read));}bis.close();return charset;}public static String readFile(String path) throws IOException {// 判断文件是否存在File file = new File(path);if (!file.exists()) {return null;}String data = null;// 获取文件编码格式String code = FileUtil.getFileEncode(path);InputStreamReader isr = null;// 根据编码格式解析文件if ("asci".equals(code)) {// 这里采用GBK编码,而不用环境编码格式,因为环境默认编码不等于操作系统编码// code = System.getProperty("file.encoding");code = "GBK";}isr = new InputStreamReader(new FileInputStream(file), code);// 读取文件内容int length = -1;char[] buffer = new char[1024];StringBuffer sb = new StringBuffer();while ((length = isr.read(buffer, 0, 1024)) != -1) {sb.append(buffer, 0, length);}data = new String(sb);isr.close();return data;}/*** 读取文件** @param fileName fileName* @param encoding encoding* @return strng* @throws Exception e* @author jiangzeyin*/public static String readToString(String fileName, String encoding) throws Exception {File file = new File(fileName);Long filelength = file.length();byte[] filecontent = new byte[filelength.intValue()];FileInputStream in = new FileInputStream(file);in.read(filecontent);in.close();return new String(filecontent, encoding);}/*** 读取文件全部内容* <p>* 默认为UTF-8** @param fileName fileName* @return str* @throws Exception e* @author jiangzeyin*/public static String readToString(String fileName) throws Exception {return readToString(fileName, "UTF-8");}/*** 写文件** @param fileName fileName* @param content content* @throws IOException io* @author jiangzeyin*/public static void writeFile(String fileName, String content) throws IOException {appendFileContext(fileName, content, false);}/*** 添加文件内容** @param fileName file* @param content c* @throws IOException io* @author jiangzeyin*/public static void appendFileContext(String fileName, String content) throws IOException {appendFileContext(fileName, content, true);}/*** 追加文件内容** @param fileName fileName* @param content c* @param append 是否是追加* @throws IOException io* @author jiangzeyin*/public static void appendFileContext(String fileName, String content, boolean append) throws IOException {File file = new File(fileName);file.getParentFile().mkdirs();Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));if (content != null)out.write(content);out.close();}public static boolean writeInputStream(InputStream inputStream, String path) throws IOException {return writeInputStream(inputStream, new File(path));}/*** @param inputStream inp* @param file file* @return boolean* @throws IOException io*/public static boolean writeInputStream(InputStream inputStream, File file) throws IOException {Assert.notNull(inputStream);Assert.notNull(file);mkdirs(file);DataOutputStream outputStream = null;try {outputStream = new DataOutputStream(new FileOutputStream(file));int len = inputStream.available();//判断长度是否大于1Mif (len <= 1024 * 1024) {byte[] bytes = new byte[len];inputStream.read(bytes);outputStream.write(bytes);} else {int byteCount = 0;//1M逐个读取byte[] bytes = new byte[1024 * 1024];while ((byteCount = inputStream.read(bytes)) != -1) {outputStream.write(bytes, 0, byteCount);}}} finally {if (inputStream != null)inputStream.close();if (outputStream != null)outputStream.close();}return true;}/*** 判断流的字符串格式** @param ins ins* @return str* @throws IOException io*/public static String getCharset(InputStream ins) throws IOException {BufferedInputStream bin = new BufferedInputStream(ins);int p = (bin.read() << 8) + bin.read();String code = null;switch (p) {case 0xefbb:code = "UTF-8";break;case 0xfffe:code = "Unicode";break;case 0xfeff:code = "UTF-16BE";break;default:code = "GBK";}ins.close();bin.close();return code;}/*** 获取文件 编码** @param fileName fileName* @return str* @throws IOException io* @author jiangzeyin*/public static String getFileCharset(String fileName) throws IOException {FileInputStream ins = new FileInputStream(fileName);return getCharset(ins);}public static String getFilePath(String path) {File file = new File(path);return getFilePath(file);}public static String getFilePath(File file) {return clearPath(file.getParent());}/*** 获取文件后缀** @param filename file* @return str* @author jiangzeyin*/public static String getFileExt(String filename) {String ext = "";int index = filename.lastIndexOf(".");if (index == -1) {return "";}ext = filename.substring(index + 1);return ext;}public static String clearPath(String input) {input = input.replace('\\', '/');return clearPath_(input);}/*** 获取文件名** @param filename file* @return s* @author jiangzeyin*/public static String getFileName(String filename) {String ext = "";int index = filename.lastIndexOf("/");if (index == -1) {return filename;}ext = filename.substring(index + 1);return ext;}private static String clearPath_(String input) {int from = 0;int j = input.indexOf("://");if (j != -1) {from = j + 3;}int i = input.indexOf("//", from);if (i == -1) {return input;}String input_ = input.substring(0, i) + "/" + input.substring(i + 2);return clearPath_(input_);}/*** 递归删除目录下的所有文件及子目录下所有文件** @param dir 将要删除的文件目录* @return boolean Returns "true" if all deletions were successful. If a* deletion fails, the method stops attempting to delete and returns* "false".*/public static boolean deleteDir(File dir) {if (dir.isDirectory()) {String[] children = dir.list();// 递归删除目录中的子目录下for (int i = 0; i < (children != null ? children.length : 0); i++) {boolean success = deleteDir(new File(dir, children[i]));if (!success) {return false;}}}// 目录此时为空,可以删除return dir.delete();}/*** 获取指定目录下的所有文件** @param path path* @return LinkedList* @author XiangZhongBao*/public static LinkedList<File> getFolderFiles(String path) {File file = new File(path);if (!file.exists())return null;if (!file.isDirectory())return null;File[] files = file.listFiles();if (files == null)return null;LinkedList<File> linkedList = new LinkedList<>();for (File item : files) {if (item.isDirectory()) {LinkedList<File> tempFile = getFolderFiles(item.getPath());if (tempFile != null)linkedList.addAll(tempFile);} else {linkedList.add(item);}}return linkedList;}/*** @param dir dir* @return boolean* @author jiangzeyin*/public static boolean deleteDir(String dir) {return deleteDir(new File(dir));}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。