对象转换工具类
map与javabean
map与实体
map与String
package cn.com.services.utils;
import com.google.common.collect.Maps;
import org.springframework.cglib.beans.BeanMap;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* 转变工具类
*/
public class ConvertUtil {
/**
* 将对象转换为map
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean ) {
Map<String, Object> map = Maps.newHashMap();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key.toString(), beanMap.get(key));
}
}
return map;
}
public static <T> Map<String, Object> beanToMap(T bean ,List<String> whiteList) {
Map<String, Object> map = Maps.newHashMap();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
if( whiteList.contains(key.toString())){
map.put(key.toString(), beanMap.get(key));
}
}
}
return map;
}
/**
* 将map转换为javabean对象
*
* @param map
* @param bean
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, T bean) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
/**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, String> object2MapST(Object obj) {
Map<String, String> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
Object o =null;
try {
for (Field field : fields) {
field.setAccessible(true);
o=field.get(obj);
map.put(field.getName(), o!=null?String.valueOf(field.get(obj)):null);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* Map转成实体对象
*
* @param map 实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
*
* Map转String
* @param map
* @return
*/
public static String getMapToString(Map<String,Object> map) {
Set<String> keySet = map.keySet();
//将set集合转换为数组
String[] keyArray = keySet.toArray(new String[keySet.size()]);
//给数组排序(升序)
Arrays.sort(keyArray);
//因为String拼接效率会很低的,所以转用StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
// 参数值为空,则不参与签名 这个方法trim()是去空格
if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) {
sb.append(keyArray[i]).append(":").append(String.valueOf(map.get(keyArray[i])).trim());
}
if (i != keyArray.length - 1) {
sb.append(",");
}
}
return sb.toString();
}
/**
*
* String转map
* @param str
* @return
*/
public static Map<String,Object> getStringToMap(String str){
//根据逗号截取字符串数组
String[] str1 = str.split(",");
//创建Map对象
Map<String,Object> map = new HashMap<>();
//循环加入map集合
for (int i = 0; i < str1.length; i++) {
//根据":"截取字符串数组
String[] str2 = str1[i].split(":");
//str2[0]为KEY,str2[1]为值
map.put(str2[0],str2[1]);
}
return map;
}
}
StrUtils
package cn.com.services.utils;
public class StrUtils {
/**
*
* @param str
* @return
*/
public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
/**
* 参数加引号处理
* @param str
* @return
*/
public static String addQuotesToParameter(String str) {
if (!StrUtils .isBlank(str)) {
String[] idsArr = str.split(",");
if (idsArr.length > 0) {
StringBuffer idBuffer = new StringBuffer();
for (int i = 0; i < idsArr.length; i++) {
idBuffer.append("'" + idsArr[i] + "',");
}
str = idBuffer.toString().substring(0, idBuffer.toString().length() - 1);
}
}
return str;
}
/**
* 去替换横杠
*
* @param str
* @return
*/
public static String getReplaseStr(String str) {
String t_str = null;
if (str != null) {
t_str = str.replace("-", "");
}
return t_str;
}
}
Excel工具类
package cn.com.services.utils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
public class ExcelExportUtils {
/**
* 使用Excel模板创建Workbook
* @param request
* @param path
* @return
*/
public static Workbook createWorkbook(HttpServletRequest request, String path){
String realPath = request.getSession().getServletContext().getRealPath("/");
File file = new File(realPath + path);
FileInputStream fis = null;
Workbook book = null;
try {
fis = new FileInputStream(file);
String suffix =path.substring(path.lastIndexOf(".") + 1);
if("xlsx".equalsIgnoreCase(suffix)){
book = new XSSFWorkbook(fis);
}else if("xls".equalsIgnoreCase(suffix)){
book = WorkbookFactory.create(fis);
}
return book;
} catch (FileNotFoundException e) {
throw new RuntimeException("文件不存在!");
} catch (IOException e) {
throw new RuntimeException("Workbook文件创建出错!");
} catch (Exception e){
e.printStackTrace();
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException("文件流关闭出错!");
}
}
}
return book;
}
/**
* 创建行或者获取行
* @param sheet
* @param index
* @return
*/
public static Row createOrGetRow(Sheet sheet, int index){
Row row = null;
row = sheet.getRow(index);
if(row != null){
return row;
}
row = sheet.createRow(index);
return row;
}
/**
* 创建单元格或者获取单元格
* @param row
* @param index
* @return
*/
public static Cell createOrGetCell(Row row, int index){
Cell cell = null;
cell = row.getCell(index);
if(cell != null){
return cell;
}
cell = row.createCell(index);
return cell;
}
/**
* 设置单元格值
* @param value
* @param cell
* @param style
*/
public static void setCellValue(String value, Cell cell, CellStyle style)
{
String reg = "^-?\\d+\\.?\\d*$";
if(StringUtils.isEmpty(value) || value == null){
cell.setCellValue("");
}else{
if(!"-".equals(value) && value.matches(reg)){
cell.setCellValue(Double.parseDouble(value)); //设置数字
}else{
cell.setCellValue(value);
}
}
if(style != null){
cell.setCellStyle(style);
}
}
/**
* 导出Excel
* @param response
* @param book
* @param fileName
*/
public static void exportExcel(HttpServletResponse response, Workbook book, String fileName, String suffix){
String excelName = "";
ServletOutputStream out = null;
try {
excelName = java.net.URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
if("xlsx".equalsIgnoreCase(suffix)){
response.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xlsx" );
}else if("xls".equalsIgnoreCase(suffix)){
response.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls" );
}
out = response.getOutputStream();
book.write(out);
out.flush();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码错误!");
} catch (IOException e) {
throw new RuntimeException("获取输出流或输出文件时出错!");
} finally{
try {
if(out != null){
out.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭输出流时出错!");
}
}
}
/**
* 下载指定路径的文件
* @param response
* @param realPath
* @param excelName
*/
public static void downloadTemplet(HttpServletResponse response,
String realPath, String excelName) {
FileInputStream fis = null;
ServletOutputStream out = null;
try {
excelName = java.net.URLEncoder.encode(excelName, "UTF-8");
fis = new FileInputStream(new File(realPath));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xlsx");
out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("文件找不到!");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException("不支持的编码错误!");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("创建输出流或输出文件时出错!");
}finally {
if(out != null){
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭输出流时出错!");
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭输入流时出错!");
}
}
}
}
/**
* 根据绝对路径创建Workbook
* @param request
* @param filePath
* @return
*/
public static Workbook createWorkbookByRealPath(HttpServletRequest request,
String filePath) {
File file = new File(filePath);
FileInputStream fis = null;
Workbook book = null;
try {
fis = new FileInputStream(file);
book = new XSSFWorkbook(fis);
return book;
} catch (FileNotFoundException e) {
throw new RuntimeException("文件不存在!");
} catch (IOException e) {
throw new RuntimeException("Workbook文件创建出错!");
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException("文件流关闭出错!");
}
}
}
}
public static String getCellValue(Workbook book, Cell cell) {
FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
if(cell == null || "".equals(cell.toString().trim())){
return null;
}
String cellValue = "";
int cellType = cell.getCellType();
if(cellType == Cell.CELL_TYPE_FORMULA){ //表达式类型
cellType = evaluator.evaluate(cell).getCellType();
}
switch (cellType) {
case Cell.CELL_TYPE_STRING: //字符串类型
cellValue = StringUtils.isEmpty(cell.getStringCellValue().trim()) ? "" : cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_BOOLEAN: //布尔类型
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC: //数值类型
if (HSSFDateUtil.isCellDateFormatted(cell)) { //判断日期类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
cellValue = format.format(cell.getDateCellValue());
} else { //否
cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());
}
break;
default: //其它类型,取空串吧
cellValue = null;
break;
}
return cellValue;
}
/**
* 将文件导出到本地
* @param path
* @param book
*/
public static void exportExcel(String path, Workbook book){
File file = new File(path);
if(!file.exists()){
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
book.write(os);
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
PoiUtils
package cn.com.services.utils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.ibatis.scripting.xmltags.OgnlCache;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataValidation;
import org.springframework.util.StringUtils;
import java.util.HashMap;
public class PoiUtils {
public static Row getRow(Sheet sheet , int rowNum){
Row row = sheet.getRow(rowNum);
if( row == null){
row = sheet.createRow(rowNum);
}
return row;
}
public static Cell getCell(Row row , int cellNum){
Cell cell = row.getCell(cellNum);
if(cell == null ){
cell = row.createCell(cellNum);
}
return cell;
}
public static Cell getCell(Sheet sheet,int row ,int cellNum){
return PoiUtils.getCell(PoiUtils.getRow(sheet,row) , cellNum);
}
public static void setRegionStyle(Sheet sheet , CellRangeAddress address, CellStyle style){
if(address == null) return;
Row row;
Cell cell;
for (int i = address.getFirstRow(); i < address.getLastRow(); i++) {
row = PoiUtils.getRow(sheet,i);
for (int j = address.getFirstColumn(); j < address.getLastColumn(); j++) {
cell = PoiUtils.getCell( row ,j);
cell.setCellStyle(style);
}
}
}
public static void main(String[] args) {
HashMap<Object, Object> t1 = Maps.newHashMap();
t1.put("ymId",201901);
HashMap<Object, Object> t2 = Maps.newHashMap();
t2.put("ymId",201901);
HashMap<Object, Object> context = Maps.newHashMap();
context.put("t1",t1);
context.put("t2",t2);
JSON.parse("{\"a\":1}");
System.out.println(OgnlCache.getValue("t1.ymId == t2.ymId",context));
}
public static void setCell(Row row, int cellNum, Double value) {
if (value != null) {
getCell(row, cellNum).setCellValue(value);
}
}
public static void setCell(Row row, int cellNum, String value) {
if (value != null) {
getCell(row, cellNum).setCellValue(value);
}
}
public static void setCell(Row row, int cellNum, String value, CellStyle cellStyle) {
if (value != null) {
Cell cell = getCell(row, cellNum);
cell.setCellStyle(cellStyle);
cell.setCellValue(value);
}
}
public static void setCell(Row row, int cellNum, Double value, CellStyle cellStyle) {
Cell cell = getCell(row, cellNum);
cell.setCellStyle(cellStyle);
setCell(cell, value);
}
public static void setCell(Cell cell, Double value) {
if (value == null) {
cell.setCellValue("-");
} else {
cell.setCellValue(value);
}
}
/**
* @param sheet 模板sheet页(需要设置下拉框的sheet)
* @param textlist 下拉框显示的内容
* @param firstRow 添加下拉框对应开始行
* @param endRow 添加下拉框对应结束行
* @param firstCol 添加下拉框对应开始列
* @param endCol 添加下拉框对应结束列
*/
public static void setHSSFValidation(XSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol){
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(textlist);
XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(
dvConstraint, addressList);
// 07默认setSuppressDropDownArrow(true);
// validation.setSuppressDropDownArrow(true);
// validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
}
FormatterUtil
package cn.com.services.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 格式转换工具类
*/
public class FormatterUtil {
/**
* 四舍五入,保留num个小数位数
*
* @param val double 需要转换的值
* @param num int 保留几位小数
* @return Double
*/
public static Double keepScale2Double(double val, int num) {
int pow = (int) Math.pow(10, num);
return (double) Math.round(val * pow) / pow;
}
/**
* 四舍五入,保留num个小数点后的数字
*
* @param val double 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String getNum(double val, int num) {
String str = "";
str = new BigDecimal(val).setScale(num, BigDecimal.ROUND_HALF_UP) + "";
return str;
}
/**
* 四舍五入,保留num个小数点后的数字
*
* @param val String 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String getNum(String val, int num) {
if(isEmpty(val) || "-".equals(val)) {
return "-";
}
if("0.0".equals(val) || "0".equals(val)) {
return val;
}
String str = "";
str = new BigDecimal(Double.parseDouble(val)).setScale(num, BigDecimal.ROUND_HALF_UP) + "";
return str;
}
/**
* 转成千分位显示
*
* @param val double 需要转换的值
* @return String
*/
public static String formatTosepara(double val) {
DecimalFormat df = new DecimalFormat("#,###");
return df.format(val);
}
/**
* 转成千分位显示
* @param val String 需要转换的值
* @return String
*/
public static String formatTosepara(String val) {
if(val == null || val.equals("-")){
return "-";
}
DecimalFormat df = new DecimalFormat("#,###");
return df.format(Double.parseDouble(val));
}
/**
* 判断是不是数字 (正整数)
* @param val String
* @return boolean
*/
public static boolean isNumeric(String val){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(val);
if( !isNum.matches() ){
return false;
}
return true;
}
/**
* 由"4367700",转为"4,368" 或 "437" (化为以千或为万为单位)
* @param val String 需要转换的值
* @param unit String 单位标识 thousand:千 || 万
* @return String
*/
public static String addThousandUnit(String val, String unit){
Pattern pattern = Pattern.compile("^\\-(\\d*\\.+\\d+)?(\\d*)?$");
if(val == null){
return val;
}
Matcher isNum = pattern.matcher(val);
if(!isNum.matches()){
return val;
}
double num = 10000;
if(unit != null && "thousand".equals(unit)){
num = 1000;
}
String result = String.format("%.1f", (Double.parseDouble(val) / num));
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
return nf.format(Double.parseDouble(result));
}
/**
* 把Double转成百分比值
*
* @param val Double 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String percentOfDouble(Double val, int num) {
if (val == null) {
return "";
}
BigDecimal b = new BigDecimal((val * 100)).setScale(num, BigDecimal.ROUND_HALF_UP);
String persentStr = b + "%";
return persentStr;
}
/**
* 转换保留一位小数
*
* @param val double
* @return double
*/
public static double getOneDecimal(double val) {
DecimalFormat dFormat = new DecimalFormat("#.0");
String yearString = dFormat.format(val);
Double temp = Double.valueOf(yearString);
return temp;
}
/**
* 转换保留两位小数
*
* @param val double
* @return double
*/
public static String getTwoDecimal(double val) {
DecimalFormat dFormat = new DecimalFormat("0.00");
String str = dFormat.format(val);
return str;
}
/**
* 字符串空判断
*
* @param val String
* @return boolean
*/
public static boolean isEmpty(String val)
{
boolean flag = true;
if(null != val && 0 != val.trim().length()) {
flag = false;
}
return flag;
}
/**
* 添加符号 +
*
* @param val String
* @return String
*/
public static String addSign(String val)
{
if(!isEmpty(val) && !val.contains("-"))
{
val = "+" + val;
}
return val;
}
/**
* 判断是否为整数(不带+号那种)
*
* @param obj Object
* @return boolean
*/
public static boolean isPositiveInteger(Object obj) {
boolean flag = false;
try {
if(obj != null){
String source = obj.toString();
Pattern pattern = Pattern.compile("^{0,1}[1-9]\\d*");
if(pattern.matcher(source).matches()){
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 判断是否为小数(不带+号那种)
*
* @param obj Object
* @return boolean
*/
public static boolean isPositiveDecimal(Object obj){
boolean flag = false;
try {
if(obj != null){
String source = obj.toString();
Pattern pattern = Pattern.compile("{0,1}[0]\\.[1-9]*|{0,1}[1-9]\\d*\\.\\d*");
if(pattern.matcher(source).matches()){
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 判断是否是整数或者是携带一位或者两位的小数
*
* @param obj Object
* @return boolean
*/
public static boolean judgeTwoDecimal(Object obj){
boolean flag = false;
try {
if(obj != null){
String source = obj.toString();
Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1,2})?$");
if(pattern.matcher(source).matches()){
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 判断当前月份是第几季度
*
* @param month int
* @return int
*/
public static int getQuarterNumbers(int month){
int nums = 0;
if(month <= 3){
nums = 1;
}else if(month > 3 && month <= 6){
nums = 2;
}else if(month > 6 && month <= 9){
nums = 3;
}else if(month > 9 && month <= 12){
nums = 4;
}
return nums;
}
/**
* 获取相应的国际化季度名称
* @return Map<String,String>
*/
public static Map<String, String> getQuarterKeysMap(){
Map<String, String> keyMap = new HashMap<String, String>();
keyMap.put("1", "common.Q1");
keyMap.put("2", "common.Q2");
keyMap.put("3", "common.Q3");
keyMap.put("4", "common.Q4");
return keyMap;
}
/**
* 处理导出的excel文件中的空格变成+号的问题
*
* @param excelName String
* @return String
*/
public static String encodeExcelName(String excelName){
try {
excelName = URLEncoder.encode(excelName, "utf-8");
excelName = excelName.replace("+", "%20");
} catch (final IOException e) {
e.printStackTrace();
} finally {}
return excelName;
}
/**
* 获取外网IP
*
* @param request HttpServletRequest
* @return String
*/
public static String getRemoteHost(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
/**
* 参数增加引号
*
* @param val String
* @return String
*/
public static String addQuotesToParameter(String val) {
if (!isEmpty(val)) {
String[] arr = val.split(",");
if (arr.length > 0) {
StringBuffer idBuffer = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
idBuffer.append("'" + arr[i] + "',");
}
val = idBuffer.toString().substring(0, idBuffer.toString().length() - 1);
}
}
return val;
}
/*
* 数字转汉字数字
*/
public static String numberToChinese(long number) {
final String[] chineseNum = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
final String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
final String[] unit_type = {"", "万", "亿"};
// 转数组
char[] numberArray = (number + "").toCharArray();
// 拼接成字符串
StringBuilder dst = new StringBuilder("");
// 循环 上次数字是否是 0
boolean zero = false;
// 单位级别
int type = numberArray.length / 4;
if (numberArray.length % 4 == 0) {
// 刚好是级别切换
type--;
}
for (int i = 0; i < numberArray.length; i++) {
int num = (int) numberArray[i] - 48;
// 判断是否到了级别切换
if (i > 0 && (numberArray.length - i) % 4 == 0) {
//级别切换时,上次为 0,补齐单位名称
if (zero) {
dst.append(unit_type[type]);
}
type--;
}
// 数字为0跳过
if (num == 0) {
zero = true;
continue;
}
// 上次为0 且不是级别切换时,添加一个零,
if (zero) {
dst.append(chineseNum[0]);
}
// 数字
dst.append(chineseNum[num]);
// 单位
if (i < numberArray.length - 1) {
dst.append(unit[numberArray.length - i - 1]);
}
// 上次数字,设置为非 0
zero = false;
}
return dst.toString().replace("一十","十");
}
}
FontUtil
package cn.com.services.utils;
public class FontUtil {
public static void main(String[] args) {
System.out.println(decodeUnicode("\u63d0\u793a\u4fe1\u606f"));
System.out.println(chinaToUnicode("提示信息"));
}
/**
* 把中文转成Unicode码
*
* @param str
* @return
*/
public static String chinaToUnicode(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
result += "\\u" + Integer.toHexString(chr1);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 判断是否为中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
//Unicode转中文
public static String decodeUnicode(final String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 0; i < hex.length; i++) {
try {
// 汉字范围 \u4e00-\u9fa5 (中文)
if(hex[i].length()>=4){//取前四个,判断是否是汉字
String chinese = hex[i].substring(0, 4);
try {
int chr = Integer.parseInt(chinese, 16);
boolean isChinese = isChinese((char) chr);
//转化成功,判断是否在 汉字范围内
if (isChinese){//在汉字范围内
// 追加成string
string.append((char) chr);
//并且追加 后面的字符
String behindString = hex[i].substring(4);
string.append(behindString);
}else {
string.append(hex[i]);
}
} catch (NumberFormatException e1) {
string.append(hex[i]);
}
}else{
string.append(hex[i]);
}
} catch (NumberFormatException e) {
string.append(hex[i]);
}
}
return string.toString();
}
}