个人的工具类

DateUtils ,MD5Utils,POIUtils,QiniuUtils,SMSUtils,ValidateCodeUtils,
日期工具类,MD5加密,excel解析,七牛云工具类,短信发送工具类,验证码随机生成。简单实用,未经允许,请勿转载

package com.itheima.utils;
import java.text.SimpleDateFormat;
import java.util.*;
/**

  • 日期操作工具类
    /
    public class DateUtils {
    /
    *
    • 日期转换- String -> Date
    • @param dateString 字符串时间
    • @return Date类型信息
    • @throws Exception 抛出异常
      /
      public static Date parseString2Date(String dateString) throws Exception {
      if (dateString == null) {
      return null;
      }
      return parseString2Date(dateString, “yyyy-MM-dd”);
      }
      /
      *
    • 日期转换- String -> Date
    • @param dateString 字符串时间
    • @param pattern 格式模板
    • @return Date类型信息
    • @throws Exception 抛出异常
      /
      public static Date parseString2Date(String dateString, String pattern) throws Exception {
      if (dateString == null) {
      return null;
      }
      SimpleDateFormat sdf = new SimpleDateFormat(pattern);
      Date date = sdf.parse(dateString);
      return date;
      }
      /
      *
    • 日期转换 Date -> String
    • @param date Date类型信息
    • @return 字符串时间
    • @throws Exception 抛出异常
      /
      public static String parseDate2String(Date date) throws Exception {
      if (date == null) {
      return null;
      }
      return parseDate2String(date, “yyyy-MM-dd”);
      }
      /
      *
    • 日期转换 Date -> String
    • @param date Date类型信息
    • @param pattern 格式模板
    • @return 字符串时间
    • @throws Exception 抛出异常
      /
      public static String parseDate2String(Date date, String pattern) throws Exception {
      if (date == null) {
      return null;
      }
      SimpleDateFormat sdf = new SimpleDateFormat(pattern);
      String strDate = sdf.format(date);
      return strDate;
      }
      /
      *
    • 获取当前日期的本周一是几号
    • @return 本周一的日期
      /
      public static Date getThisWeekMonday() {
      Calendar cal = Calendar.getInstance();
      cal.setTime(new Date());
      // 获得当前日期是一个星期的第几天
      int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
      if (1 == dayWeek) {
      cal.add(Calendar.DAY_OF_MONTH, -1);
      }
      // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
      cal.setFirstDayOfWeek(Calendar.MONDAY);
      // 获得当前日期是一个星期的第几天
      int day = cal.get(Calendar.DAY_OF_WEEK);
      // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
      cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
      return cal.getTime();
      }
      /
      *
    • 获取当前日期周的最后一天
    • @return 当前日期周的最后一天
      /
      public static Date getSundayOfThisWeek() {
      Calendar c = Calendar.getInstance();
      int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
      if (dayOfWeek == 0) {
      dayOfWeek = 7;
      }
      c.add(Calendar.DATE, -dayOfWeek + 7);
      return c.getTime();
      }
      /
      *
    • 根据日期区间获取月份列表
    • @param minDate 开始时间
    • @param maxDate 结束时间
    • @return 月份列表
    • @throws Exception
      /
      public static List getMonthBetween(String minDate, String maxDate, String format) throws Exception {
      ArrayList result = new ArrayList<>();
      SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM”);
      Calendar min = Calendar.getInstance();
      Calendar max = Calendar.getInstance();
      min.setTime(sdf.parse(minDate));
      min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
      max.setTime(sdf.parse(maxDate));
      max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
      SimpleDateFormat sdf2 = new SimpleDateFormat(format);
      Calendar curr = min;
      while (curr.before(max)) {
      result.add(sdf2.format(curr.getTime()));
      curr.add(Calendar.MONTH, 1);
      }
      return result;
      }
      /
      *
    • 根据日期获取年度中的周索引
    • @param date 日期
    • @return 周索引
    • @throws Exception
      /
      public static Integer getWeekOfYear(String date) throws Exception {
      Date useDate = parseString2Date(date);
      Calendar cal = Calendar.getInstance();
      cal.setTime(useDate);
      return cal.get(Calendar.WEEK_OF_YEAR);
      }
      /
      *
    • 根据年份获取年中周列表
    • @param year 年分
    • @return 周列表
    • @throws Exception
      /
      public static Map<Integer, String> getWeeksOfYear(String year) throws Exception {
      Date useDate = parseString2Date(year, “yyyy”);
      Calendar cal = Calendar.getInstance();
      cal.setTime(useDate);
      //获取年中周数量
      int weeksCount = cal.getWeeksInWeekYear();
      Map<Integer, String> mapWeeks = new HashMap<>(55);
      for (int i = 0; i < weeksCount; i++) {
      cal.get(Calendar.DAY_OF_YEAR);
      mapWeeks.put(i + 1, parseDate2String(getFirstDayOfWeek(cal.get(Calendar.YEAR), i)));
      }
      return mapWeeks;
      }
      /
      *
    • 获取某年的第几周的开始日期
    • @param year 年分
    • @param week 周索引
    • @return 开始日期
    • @throws Exception
      /
      public static Date getFirstDayOfWeek(int year, int week) throws Exception {
      Calendar c = new GregorianCalendar();
      c.set(Calendar.YEAR, year);
      c.set(Calendar.MONTH, Calendar.JANUARY);
      c.set(Calendar.DATE, 1);
      Calendar cal = (GregorianCalendar) c.clone();
      cal.add(Calendar.DATE, week * 7);
      return getFirstDayOfWeek(cal.getTime());
      }
      /
      *
    • 获取某年的第几周的结束日期
    • @param year 年份
    • @param week 周索引
    • @return 结束日期
    • @throws Exception
      /
      public static Date getLastDayOfWeek(int year, int week) throws Exception {
      Calendar c = new GregorianCalendar();
      c.set(Calendar.YEAR, year);
      c.set(Calendar.MONTH, Calendar.JANUARY);
      c.set(Calendar.DATE, 1);
      Calendar cal = (GregorianCalendar) c.clone();
      cal.add(Calendar.DATE, week * 7);
      return getLastDayOfWeek(cal.getTime());
      }
      /
      *
    • 获取当前时间所在周的开始日期
    • @param date 当前时间
    • @return 开始时间
      /
      public static Date getFirstDayOfWeek(Date date) {
      Calendar c = new GregorianCalendar();
      c.setFirstDayOfWeek(Calendar.SUNDAY);
      c.setTime(date);
      c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
      return c.getTime();
      }
      /
      *
    • 获取当前时间所在周的结束日期
    • @param date 当前时间
    • @return 结束日期
      */
      public static Date getLastDayOfWeek(Date date) {
      Calendar c = new GregorianCalendar();
      c.setFirstDayOfWeek(Calendar.SUNDAY);
      c.setTime(date);
      c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
      return c.getTime();
      }
      //获得上周一的日期
      public static Date geLastWeekMonday(Date date) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(getThisWeekMonday(date));
      cal.add(Calendar.DATE, -7);
      return cal.getTime();
      }
      //获得本周一的日期
      public static Date getThisWeekMonday(Date date) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(date);
      // 获得当前日期是一个星期的第几天
      int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
      if (1 == dayWeek) {
      cal.add(Calendar.DAY_OF_MONTH, -1);
      }
      // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
      cal.setFirstDayOfWeek(Calendar.MONDAY);
      // 获得当前日期是一个星期的第几天
      int day = cal.get(Calendar.DAY_OF_WEEK);
      // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
      cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
      return cal.getTime();
      }
      //获得下周一的日期
      public static Date getNextWeekMonday(Date date) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(getThisWeekMonday(date));
      cal.add(Calendar.DATE, 7);
      return cal.getTime();
      }
      //获得今天日期
      public static Date getToday(){
      return new Date();
      }
      //获得本月一日的日期
      public static Date getFirstDay4ThisMonth(){
      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.DAY_OF_MONTH,1);
      return calendar.getTime();
      }
      public static void main(String[] args) {
      try {
      System.out.println(“本周一” + parseDate2String(getThisWeekMonday()));
      System.out.println(“本月一日” + parseDate2String(getFirstDay4ThisMonth()));
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }

package com.itheima.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
/**
* 使用md5的算法进行加密
*/
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance(“md5”).digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(“没有md5这个算法!”);
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = “0” + md5code;
}
return md5code;
}

public static void main(String[] args) {
	System.out.println(md5("1234"));
}

}

package com.itheima.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
public class POIUtils {
private final static String xls = “xls”;
private final static String xlsx = “xlsx”;
private final static String DATE_FORMAT = “yyyy/MM/dd”;
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException {
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}

//校验文件是否合法
public static void checkFile(MultipartFile file) throws IOException{
    //判断文件是否存在
    if(null == file){
        throw new FileNotFoundException("文件不存在!");
    }
    //获得文件名
    String fileName = file.getOriginalFilename();
    //判断文件是否是excel文件
    if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
        throw new IOException(fileName + "不是excel文件");
    }
}
public static Workbook getWorkBook(MultipartFile file) {
    //获得文件名
    String fileName = file.getOriginalFilename();
    //创建Workbook工作薄对象,表示整个excel
    Workbook workbook = null;
    try {
        //获取excel文件的io流
        InputStream is = file.getInputStream();
        //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
        if(fileName.endsWith(xls)){
            //2003
            workbook = new HSSFWorkbook(is);
        }else if(fileName.endsWith(xlsx)){
            //2007
            workbook = new XSSFWorkbook(is);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return workbook;
}
public static String getCellValue(Cell cell){
    String cellValue = "";
    if(cell == null){
        return cellValue;
    }
    //如果当前单元格内容为日期类型,需要特殊处理
    String dataFormatString = cell.getCellStyle().getDataFormatString();
    if(dataFormatString.equals("m/d/yy")){
        cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
        return cellValue;//"2019/10/10"
    }
    //把数字当成String来读,避免出现1读成1.0的情况
    if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
        cell.setCellType(Cell.CELL_TYPE_STRING);
    }
    //判断数据的类型
    switch (cell.getCellType()){
        case Cell.CELL_TYPE_NUMERIC: //数字
            cellValue = String.valueOf(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING: //字符串
            cellValue = String.valueOf(cell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_BOOLEAN: //Boolean
            cellValue = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA: //公式
            cellValue = String.valueOf(cell.getCellFormula());
            break;
        case Cell.CELL_TYPE_BLANK: //空值
            cellValue = "";
            break;
        case Cell.CELL_TYPE_ERROR: //故障
            cellValue = "非法字符";
            break;
        default:
            cellValue = "未知类型";
            break;
    }
    return cellValue;
}

}

package com.itheima.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**

  • 七牛云工具类
    */
    public class QiniuUtils {
    public static String accessKey = “dulF9Wze9bxujtuRvu3yyYb9JX1Sp23jzd3tO708”;
    public static String secretKey = “vZkhW7iot3uWwcWz9vXfbaP4JepdWADFDHVLMZOe”;
    public static String bucket = “itcasthealth_space_1”;

    public static void upload2Qiniu(String filePath,String fileName){
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    try {
    Response response = uploadManager.put(filePath, fileName, upToken);
    //解析上传成功的结果
    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    } catch (QiniuException ex) {
    Response r = ex.response;
    try {
    System.err.println(r.bodyString());
    } catch (QiniuException ex2) {
    //ignore
    }
    }
    }

    //上传文件
    public static void upload2Qiniu(byte[] bytes, String fileName){
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //…其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

     //默认不指定key的情况下,以文件内容的hash值作为文件名
     String key = fileName;
     Auth auth = Auth.create(accessKey, secretKey);
     String upToken = auth.uploadToken(bucket);
     try {
         Response response = uploadManager.put(bytes, key, upToken);
         //解析上传成功的结果
         DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
         System.out.println(putRet.key);
         System.out.println(putRet.hash);
     } catch (QiniuException ex) {
         Response r = ex.response;
         System.err.println(r.toString());
         try {
             System.err.println(r.bodyString());
         } catch (QiniuException ex2) {
             //ignore
         }
     }
    

    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName){
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    String key = fileName;
    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
    bucketManager.delete(bucket, key);
    } catch (QiniuException ex) {
    //如果遇到异常,说明删除失败
    System.err.println(ex.code());
    System.err.println(ex.response.toString());
    }
    }
    }

package com.itheima.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**

  • 短信发送工具类
    /
    public class SMSUtils {
    public static final String VALIDATE_CODE = “SMS_206536012”;//发送短信验证码"SMS_206536012";//
    public static final String ORDER_NOTICE = “SMS_206536012”;//体检预约成功通知
    /
    *

    • 发送短信
    • @param phoneNumbers
    • @param param
    • @throws ClientException
      */
      public static void sendShortMessage(String templateCode,String phoneNumbers,String param) throws ClientException{
      // 设置超时时间-可自行调整
      System.setProperty(“sun.net.client.defaultConnectTimeout”, “10000”);
      System.setProperty(“sun.net.client.defaultReadTimeout”, “10000”);
      // 初始化ascClient需要的几个参数
      final String product = “Dysmsapi”;// 短信API产品名称(短信产品名固定,无需修改)
      final String domain = “dysmsapi.aliyuncs.com”;// 短信API产品域名(接口地址固定,无需修改)
      // 替换成你的AK
      final String accessKeyId = “LTAI4FySezCz3Rz6U2AvB3om”;// 你的accessKeyId,参考本文档步骤2
      final String accessKeySecret = “II3LmXxsejmNeHk8hNzosZCcZxl9Yp”;// 你的accessKeySecret,参考本文档步骤2
      // 初始化ascClient,暂时不支持多region(请勿修改)
      IClientProfile profile = DefaultProfile.getProfile(“cn-hangzhou”, accessKeyId, accessKeySecret);
      DefaultProfile.addEndpoint(“cn-hangzhou”, “cn-hangzhou”, product, domain);
      IAcsClient acsClient = new DefaultAcsClient(profile);
      // 组装请求对象
      SendSmsRequest request = new SendSmsRequest();
      // 使用post提交
      request.setMethod(MethodType.POST);
      // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
      request.setPhoneNumbers(phoneNumbers);
      // 必填:短信签名-可在短信控制台中找到
      request.setSignName(“传智健康”);
      // 必填:短信模板-可在短信控制台中找到
      request.setTemplateCode(templateCode);
      // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的 n a m e , 您 的 验 证 码 为 {name},您的验证码为 name,{code}“时,此处的值为
      // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\r\n,否则会导致JSON在服务端解析失败
      request.setTemplateParam(”{“code”:""+param+""}");
      // 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
      // request.setSmsUpExtendCode(“90997”);
      // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
      // request.setOutId(“yourOutId”);
      // 请求失败这里会抛ClientException异常
      SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
      if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(“OK”)) {
      // 请求成功
      System.out.println(“请求成功”);
      }
      }

    public static void main(String[] args) throws ClientException {

     SMSUtils.sendShortMessage("SMS_206536012","15707652791","1234");
    
     System.out.println("发送成功");
    

    }
    }

package com.itheima.utils;

import java.util.Random;

/**

  • 随机生成验证码工具类
    /
    public class ValidateCodeUtils {
    /
    *

    • 随机生成验证码
    • @param length 长度为4位或者6位
    • @return
      */
      public static Integer generateValidateCode(int length){
      Integer code =null;
      if(length == 4){
      code = new Random().nextInt(9999);//生成随机数,最大为9999
      if(code < 1000){
      code = code + 1000;//保证随机数为4位数字
      }
      }else if(length == 6){
      code = new Random().nextInt(999999);//生成随机数,最大为999999
      if(code < 100000){
      code = code + 100000;//保证随机数为6位数字
      }
      }else{
      throw new RuntimeException(“只能生成4位或6位数字验证码”);
      }
      return code;
      }

    /**

    • 随机生成指定长度字符串验证码
    • @param length 长度
    • @return
      */
      public static String generateValidateCode4String(int length){
      Random rdm = new Random();
      String hash1 = Integer.toHexString(rdm.nextInt());
      String capstr = hash1.substring(0, length);
      return capstr;
      }
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值