java常用工具类封装
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;
public class CommonUtil {
public static String safeToString(Object value, String defaultValue) {
if (value != null) {
return StringUtils.trim(String.valueOf(value));
}
return defaultValue;
}
public static Integer safeToInteger (Object obj, Integer defaultValue) {
if (obj != null) {
return Integer.parseInt(String.valueOf(obj));
}
return defaultValue;
}
/**
* 方法注释: 银行卡号脱敏
* @return
*/
public static String getHideCardNo(String cardNo){
if (StringUtils.isNotBlank(cardNo)) {
StringBuffer cardBuffer = new StringBuffer();
char[] card = cardNo.toCharArray();
if (card.length > 8 && card.length <= 12) {
card[card.length - 5] = '*';
card[card.length - 6] = '*';
card[card.length - 7] = '*';
card[card.length - 8] = '*';
}
if (card.length > 12) {
for (int i = 5; i <= 12; i++) {
card[card.length - i] = '*';
}
}
int head = card.length%4 + 4;
for (int i = 0; i < head; i++) {
cardBuffer.append(card[i]);
}
cardBuffer.append("");
for (int i = 0; (i + head)< card.length; i++) {
cardBuffer.append(card[i + head]);
if ((i+1)%4 == 0) {
cardBuffer.append("");
}
}
return cardBuffer.toString().trim();
}
return cardNo;
}
/**
* 名字脱敏
* 规则,张三丰,脱敏为:**丰
*/
public static String nameDesensitization(String name){
if(name==null || name.isEmpty()){
return "";
}
String myName = null;
char[] chars = name.toCharArray();
if(chars.length==1){
myName=name;
}
if(chars.length==2){
myName=name.replace(name.substring(0,1), "*");
}
if(chars.length>2){
myName=name.replaceAll(name.substring(0, chars.length-1), "*");
}
return myName;
}
/**
* 对手机号进行脱敏
* @param phone
* @return
*/
public static String getHidePhone (String phone) {
if (StringUtils.isNotBlank(phone)) {
phone = phone.replaceAll("(^\\d{3})\\d.*(\\d{4})", "$1****$2");
}
return phone;
}
/**
* 对身份证号进行脱敏
* @param idNumber
* @return
*/
public static String desensitizedIdNumber(String idNumber){
if (StringUtils.isNotBlank(idNumber)) {
if (idNumber.length() == 15){
idNumber = idNumber.replaceAll("(\\w{3})\\w*(\\w{4})", "$1********$2");
}
if (idNumber.length() == 18){
idNumber = idNumber.replaceAll("(\\w{3})\\w*(\\w{4})", "$1***********$2");
}
}
return idNumber;
}
/**
* 元转为无小数点的分
*
* @param price
* @return
*/
public static BigDecimal yuan2Fen(BigDecimal price) {
return new BigDecimal(price.multiply(new BigDecimal("100")).longValue());
}
public static void main(String[] args) {
String idNumber = desensitizedIdNumber("421202199805060221");
System.out.println(idNumber);
}
}