常用工具类(未完待续…)
说明:
这里整理了自己封装好的常用工具类
1.时间操作的工具类
package com.shaoming;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatUtil {
private static SimpleDateFormat sdf = null;
/**
*
* @param date 时间(java.util.Date)
* @param pattern 时间格式
* @return 格式化后的时间字符窜
*/
public static String dateToString(Date date, String pattern) {
sdf = new SimpleDateFormat(pattern);
String strDate = sdf.format(date);
return strDate;
}
/**
*
* @param date
* @param pattern
* @return 返回的时间
*/
public static Date stringToDate(String strDate, String pattern) {
sdf = new SimpleDateFormat(pattern);
Date parseDate = null;
try {
parseDate = sdf.parse(strDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new RuntimeException("字符串到时间(java.util.Date)格式化错误");
}
return parseDate;
}
}
2.操作json的工具类
2.1 jackson
package com.shaoming;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;
import cn.hutool.core.util.StrUtil;
/**
* jsonUtil工具类
*
* @author ryz
* @since 2020-05-11
*/
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
/**
* 对象转Json格式字符串
* @param obj 对象
* @return Json格式字符串
*/
public static <T> String obj2String(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 对象转Json格式字符串(格式化的Json字符串)
* @param obj 对象
* @return 美化的Json格式字符串
*/
public static <T> String obj2StringPretty(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 字符串转换为自定义对象
* @param str 要转换的字符串
* @param clazz 自定义对象的class对象
* @return 自定义对象
*/
public static <T> T jsonToObj(String str, Class<T> clazz){
if(StrUtil.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class) ? (T) str : mapper.readValue(str, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 集合对象与Json字符串之间的转换
* @param str 要转换的字符串
* @param typeReference 集合类型如List<Object>
* @param <T>
* @return
*/
public static <T> T jsonToObj(String str, TypeReference<T> typeReference) {
if (StrUtil.isEmpty(str) || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? str : mapper.readValue(str, typeReference));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 集合对象与Json字符串之间的转换
* @param str 要转换的字符串
* @param collectionClazz 集合类型
* @param elementClazzes 自定义对象的class对象
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzes) {
JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
try {
return mapper.readValue(str, javaType);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
2.2 fastjson
package com.shaoming.常用工具类的封装;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
*
* @Description: 基于fastjson封装的json转换工具类
* @author hbb
* @date 2019年1月1日
*
*/
public class FastJsonUtil {
/**
* 功能描述:把JSON数据转换成指定的java对象
*
* @param jsonData JSON数据
* @param clazz 指定的java对象
* @return 指定的java对象
*/
public static <T> T getJsonToBean(String jsonData, Class<T> clazz) {
return JSON.parseObject(jsonData, clazz);
}
/**
* 功能描述:把java对象转换成JSON数据
*
* @param object java对象
* @return JSON数据
*/
public static String getBeanToJson(Object object) {
return JSON.toJSONString(object);
}
/**
* 功能描述:把JSON数据转换成指定的java对象列表
*
* @param jsonData JSON数据
* @param clazz 指定的java对象
* @return List<T>
*/
public static <T> List<T> getJsonToList(String jsonData, Class<T> clazz) {
return JSON.parseArray(jsonData, clazz);
}
/**
* 功能描述:把JSON数据转换成较为复杂的List<Map<String, Object>>
*
* @param jsonData JSON数据
* @return List<Map<String, Object>>
*/
public static List<Map<String, Object>> getJsonToListMap(String jsonData) {
return JSON.parseObject(jsonData, new TypeReference<List<Map<String, Object>>>() {
});
}
}
2.3 gson
package com.shaoming;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
*
* @Description: 基于Gson封装的jsonUtil
* @author hbb
* @date 2019年1月1日
*
*/
public class GsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private GsonUtil() {
}
/**
* 对象转成json
*
* @param object
* @return json
*/
public static String objectToJson(Object object) {
String json = null;
if (gson != null) {
json = gson.toJson(object);
}
return json;
}
/**
* Json转成对象
*
* @param json
* @param cls
* @return 对象
*/
public static <T> T gsonToBean(String json, Class<T> cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(json, cls);
}
return t;
}
/**
* json转成list<T>
*
* @param json
* @param cls
* @return list<T>
*/
public static <T> List<T> gsonToList(String json, Class<T> cls) {
List<T> list = null;
if (gson != null) {
list = gson.fromJson(json, new TypeToken<List<T>>() {
}.getType());
}
return list;
}
/**
* json转成list中有map的
*
* @param json
* @return List<Map<String, T>>
*/
public static <T> List<Map<String, T>> gsonToListMaps(String json) {
List<Map<String, T>> list = null;
if (gson != null) {
list = gson.fromJson(json, new TypeToken<List<Map<String, T>>>() {
}.getType());
}
return list;
}
/**
* json转成map的
*
* @param json
* @return Map<String, T>
*/
public static <T> Map<String, T> gsonToMaps(String json) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(json, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
}
3.spring工厂获取工具类
说明:
在springboot项目中可以获取spring工厂
通过获取的spring工厂,从工厂中获取spring管理的javabean
此工具类有两种方法获取spring工厂的javabean
1.通过id获取
2.通过类名获取
package com.shaoming.常用工具类的封装;
//用来获取springboot创建好的工厂
@Component // 此类必须交给springboot管理
public class ApplicationContextUtils implements ApplicationContextAware {
// 保留下来工厂
private static ApplicationContext applicationContext;
// 将创建好工厂以参数形式传递给这个类
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.applicationContext = applicationContext;
}
// 根据类在工厂的唯一id从spring容器中获取javabean
public static Object getBeanById(String beanName) {
return applicationContext.getBean(beanName);
}
// 根据class的名字从spring容器中获取javabean
public static <T> T getBeanByName(Class<T> targetClass) {
return applicationContext.getBean(targetClass);
}
}
4.redis的配置和工具类(不足以后补充)
4.1 操作jedis
- jedis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=root
说明:
密码可以选择性的设置,一般自己测试不需要设置密码
- JedisConfig.java
package com.shaoming.redis.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import redis.clients.jedis.Jedis;
@Configuration //标识配置类 xml配置
//引入主启动类所在项目的配置文件.
@PropertySource("classpath:/properties/jedis.properties")
public class JedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Value("${redis.password}")
private String password;
//默认单例对象,修改为多例对象.
@Scope("prototype")
@Bean
public Jedis jedis() {
Jedis jedis = new Jedis(host,port);
//需要密码是在匹配
//jedis.auth(password);
return jedis;
}
}
4.2 操作RedisTemplate
说明:
springboot提供了操作redis的两个模板
StringRedisTemplate和RedisTemplate
StringRedisTemplate正常不需要配置,操作的key-value都是字符窜
- RedisConfig
package com.ckf.springboot_mysql_redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author PIGS
* @version 1.0
* @date 2020/4/8 18:11
* @effect :
*/
@Slf4j
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
- RedisUtil
package com.ckf.springboot_mysql_redis.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author 安详的苦丁茶
* @version 1.0
* @date 2020/4/8 18:12
* @effect :
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 判断 key 是否存在
*
* @param key 键
* @return 如果存在 key 则返回 true,否则返回 false
*/
public Boolean exists(String key) {
return redisTemplate.hasKey(key);
}
/**
* 获取 Key 的类型
*
* @param key 键
*/
public String type(String key) {
DataType dataType = redisTemplate.type(key);
assert dataType != null;
return dataType.code();
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return 30
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除 key
*
* @param key 键
*/
public Long delete(String... key) {
if (key == null || key.length < 1) {
return 0L;
}
return redisTemplate.delete(Arrays.asList(key));
}
/**
* 获取所有的keys
*
* @return
*/
public Set<String> keys() {
Set<String> keys1 = redisTemplate.keys("*");
return keys1;
}
/**
* 获取所有的keys得所有的值
*
* @param keys
* @return
*/
public HashMap<Object, Object> getKeysValue(String keys) {
Set<String> keys1 = redisTemplate.keys("*");
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
for (String s : keys1) {
Object o = redisTemplate.opsForValue().get(keys + s);
System.out.println("o=" + o);
hashMap.put(keys1, o);
}
return hashMap;
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return 274
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return 285
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return 295
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> getList(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
5.BigDecimal封装的工具类,±*/
package com.shaoming;
import java.math.BigDecimal;
/**
*
* @ClassName: BigDecimalUtil
* @Description: TODO(这里用一句话描述这个类的作用)
* double数据类型的加减乘除运算的工具类
* @author shaoming
* @date 2020年9月11日
*
*/
public class BigDecimalUtil {
private BigDecimalUtil() {
}
public static BigDecimal add(double v1, double v2) {// v1 + v2
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
public static BigDecimal sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
public static BigDecimal mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
public static BigDecimal div(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
// 2 = 保留小数点后两位 ROUND_HALF_UP = 四舍五入
return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);// 应对除不尽的情况
}
}
6.生成图片验证码的工具类
VerifyCodeUtils
package com.shaoming;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
*@创建人 cx
*@创建时间 2018/11/27 17:36
*@描述 验证码生成
*/
public class VerifyCodeUtils{
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
说明:
此工具类用的方法不多,粘贴复制就可以使用,不需要引入依赖
使用参考我的博客
https://blog.csdn.net/shaoming314/article/details/108790269
7.base64操作String的工具类
package com.shaoming.常用工具类的封装;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Util {
/**
* String content = "这是需要Base64编码的内容"; // 创建一个Base64编码器 BASE64Encoder
* base64Encoder = new BASE64Encoder(); // 执行Base64编码操作 String encodedString =
* base64Encoder.encode(content.getBytes("UTF-8"));
*
* System.out.println( encodedString ); // 创建Base64解码器 BASE64Decoder
* base64Decoder = new BASE64Decoder(); // 解码操作 byte[] bytes =
* base64Decoder.decodeBuffer(encodedString);
*
* String str = new String(bytes, "UTF-8");
*
* System.out.println(str); }
*
*/
private static BASE64Encoder base64Encoder = null;
private static BASE64Decoder base64Decoder = null;
static {
base64Encoder = new BASE64Encoder();
base64Decoder = new BASE64Decoder();
}
// 对字符窜进行base64编码
public static String encode(String isEncodedString) {
String encodeed = null;
try {
encodeed = base64Encoder.encode(isEncodedString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("对string字符串进行base64编码失败");
}
return encodeed;
}
// 对字符窜进行base64进行解码
public static String decode(String encodedString) {
String encodedStringed = null;
try {
byte[] bytes = base64Decoder.decodeBuffer(encodedString);
encodedStringed = new String(bytes, "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedStringed;
}
}
使用demo参照我的博客
https://blog.csdn.net/shaoming314/article/details/108810539
8.获取maven工程的properties
说明:
使用了第三方依赖Hutool
获取maven工程的resources目录下properties文件的配置信息
package com.shaoming.常用工具类的封装;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import cn.hutool.core.io.resource.ClassPathResource;
/**
*
* @ClassName: PropertiesUtil
* @Description: TODO(这里用一句话描述这个类的作用) 获取项目的properties文件
* maven项目的properties放在src/main/resource目录下
* 使用该工具类的前提是:
* 需要导入hutool这个工具里
* 因为ClassPathResource这个类是引用的Hutool这个工具集内
* @author shaoming
* @date 2020年9月17日
*
*/
public class PropertiesUtil {
private static ClassPathResource classPathResource = null;
private static Properties properties = null;
private static InputStream stream = null;
/**
* 说明:
* filePathName
* 如果配置文件在src/main/resource目录下,那么直接写文件名读取到
* 如果配置文件在src/main/resource自定义的文件夹下,要加上文件夹名称
* @param filePathName
* @return 返回配置文件信息
*/
public static Properties getPropertiesFile(String filePathName) {
try {
classPathResource = new ClassPathResource(filePathName);
properties = new Properties();
stream = classPathResource.getStream();
properties.load(stream);
} catch (Exception e) {
throw new RuntimeException("文件没找到异常!!!");
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
stream = null;
}
}
}
return properties;
}
}
9.springmvc文件上传下载的工具类
说明:
是springmvc,此工具类在springboot中不可以使用
因为上传文件的目录在war包所在的tomcat中,springboot内嵌了tomcat,所以不可以使用此工具类进行文件上传
注意事项:
我们要创建文件夹在src/main/webapp目录下(我使用的是eclipse,idea具体操作不清楚)
名字就工具类属性uploadFileName的值
FileUploadAndDownUtils
package com.shaoming.常用工具类的封装;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpStatus;
/**
*
* @ClassName: FileUtil
* @Description: TODO(这里用一句话描述这个类的作用) 文件上传下载的工具类
* @author shaoming
* @date 2020年9月15日
*
*/
public class FileUploadAndDownUtils {
private static final String uploadFileName = "upresource";
/**
* 文件上传工具类 说明: 文件加需要自家建 upresource
*
* @param myfiles
* @param request
*/
public static void fileUpload(MultipartFile[] myfiles, HttpServletRequest request) {
for (MultipartFile file : myfiles) {
// 此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
if (file.isEmpty()) {
System.out.println("文件未上传!");
} else {
// 得到上传的文件名
String fileName = file.getOriginalFilename();
// 得到服务器项目发布运行所在地址
String uploadPath = request.getSession().getServletContext().getRealPath(uploadFileName)
+ File.separator;
// 此处未使用UUID来生成唯一标识,用日期做为标识
// String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new
// Date() + fileName;
// 查看文件上传路径,方便查找
String path = uploadPath + "/" + fileName;
// 把文件上传至path的路径
File localFile = new File(path);
try {
file.transferTo(localFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 最后的文件名加上日期
*
* @param myfiles 上传文件实例
* @param request
*/
public static void fileUploadFileNameByDate(MultipartFile[] myfiles, HttpServletRequest request) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String strDate = sdf.format(date);
for (MultipartFile file : myfiles) {
// 此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
if (file.isEmpty()) {
System.out.println("文件未上传!");
} else {
// 得到上传的文件名
String fileName = file.getOriginalFilename();
// 得到服务器项目发布运行所在地址
String uploadPath = request.getSession().getServletContext().getRealPath(uploadFileName)
+ File.separator;
// 此处未使用UUID来生成唯一标识,用日期做为标识
// String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new
// Date() + fileName;
// 查看文件上传路径,方便查找
String finalFileName = strDate + fileName;
String path = uploadPath + "/" + finalFileName;
// 把文件上传至path的路径
File localFile = new File(path);
try {
file.transferTo(localFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
*
* @param request HttpServletRequest对象
* @return 上传列表文件名集合
*/
public static List<String> getUploadFileOfFileName(HttpServletRequest request) {
List<String> fileNameList = new ArrayList<String>();
String path = request.getSession().getServletContext().getRealPath(uploadFileName) + File.separator;
File[] ls = FileUtil.ls(path);
for (File file : ls) {
String name = FileUtil.getName(file);
fileNameList.add(name);
}
return fileNameList;
}
/**
*
* @param myfiles 上传的文件
* @param request HttpServletRequest对象
* @param uploadFileName 上传文件的文件夹名称(说明:这一般都是事先定义好的)
*/
public static void fileUploadFileNameByDateByPath(MultipartFile[] myfiles, HttpServletRequest request,
String uploadFileName) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String strDate = sdf.format(date);
for (MultipartFile file : myfiles) {
// 此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
if (file.isEmpty()) {
System.out.println("文件未上传!");
} else {
// 得到上传的文件名
String fileName = file.getOriginalFilename();
// 得到服务器项目发布运行所在地址
String uploadPath = request.getSession().getServletContext().getRealPath(uploadFileName)
+ File.separator;
// 此处未使用UUID来生成唯一标识,用日期做为标识
// String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new
// Date() + fileName;
// 查看文件上传路径,方便查找
String finalFileName = strDate + fileName;
String path = uploadPath + "/" + finalFileName;
// 把文件上传至path的路径
File localFile = new File(path);
try {
file.transferTo(localFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 文件下载
*
* @param request HttpServletRequest对象
* @param response HttpServletResponse对象
* @param fileName 文件名
* @param uploadFileName 上传文件夹的文件名
*/
public static ResponseEntity<byte[]> downFile(String mypicname, HttpServletRequest request) {
// 读取文件保存的根位置
if (mypicname == null) {
throw new RuntimeException("文件名为空异常");
}
String realPath = request.getSession().getServletContext().getRealPath("/" + uploadFileName);
File file = new File(realPath + "/" + mypicname);
HttpHeaders header = new HttpHeaders();
try {
header.setContentDispositionFormData("attachment", URLEncoder.encode(mypicname, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException("文件名为中文乱码解决错误");
}
ResponseEntity<byte[]> re = null;
try {
re = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
return re;
}
}