Func.java 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. package com.happy.Until;
  2. import org.apache.commons.lang.StringUtils;
  3. import java.beans.BeanInfo;
  4. import java.beans.IntrospectionException;
  5. import java.beans.Introspector;
  6. import java.beans.PropertyDescriptor;
  7. import java.io.File;
  8. import java.lang.reflect.Field;
  9. import java.lang.reflect.Modifier;
  10. import java.math.BigDecimal;
  11. import java.net.URL;
  12. import java.text.DecimalFormat;
  13. import java.text.ParseException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.*;
  16. import java.util.Map.Entry;
  17. import java.util.regex.Matcher;
  18. import java.util.regex.Pattern;
  19. /**
  20. * 公共函数类库
  21. *
  22. * @author xieli
  23. */
  24. public class Func {
  25. /**
  26. * 浮点型零值(判断"0.0"值)
  27. */
  28. public static final double FLOAT_ZERO_VALUE = 0.0000001;
  29. public static final String PATTERN = "^[-]?([0-9]+)(\\.[0-9]+)?$";
  30. public static final String PATTERN_DOT_2 = "^[-]?([0-9]+)(\\.[0-9]{1,2}+)?$";
  31. public static final String PATTERN_DOT_3 = "^[-]?([0-9]+)(\\.[0-9]{1,3}+)?$";
  32. public static final String PATTERN_NUMDOT = "^\\d+(\\.\\d+)?+(\\.\\d+)?+(\\.\\d+)?+(\\.\\d+)?+(\\.\\d+)?";
  33. private static DecimalFormat df = new DecimalFormat("#.##########");
  34. /**
  35. * map转java对象
  36. * @param clazz
  37. * @param map
  38. * @return
  39. * @throws Exception
  40. */
  41. public static Object convertToObject(Class clazz, Map<String, Object> map) {
  42. if (clazz == null || map == null || map.isEmpty())
  43. return null;
  44. BeanInfo bi = null;
  45. Object obj = null;
  46. try {
  47. bi = Introspector.getBeanInfo(clazz);
  48. obj = clazz.newInstance();
  49. PropertyDescriptor[] pds = bi.getPropertyDescriptors();
  50. String pName;
  51. for (PropertyDescriptor pd : pds) {
  52. pName = pd.getName();
  53. if (map.containsKey(pName)) {
  54. try {
  55. if (pd.getPropertyType().getName().equals("java.lang.Long")) {
  56. if (StringUtils.isNotEmpty(map.get(pName).toString())) {
  57. pd.getWriteMethod().invoke(obj, Long.parseLong(map.get(pName).toString()));
  58. }
  59. } else {
  60. pd.getWriteMethod().invoke(obj, map.get(pName));
  61. }
  62. } catch (Exception ex) {
  63. }
  64. }
  65. }
  66. } catch (Exception e) {
  67. throw new RuntimeException(e);
  68. }
  69. return obj;
  70. }
  71. /**
  72. * 加法运算(准确计算精度)
  73. *
  74. * @param o1
  75. * @param o2
  76. * @return
  77. */
  78. public static double add(Object o1, Object o2) {
  79. BigDecimal b1 = null;
  80. BigDecimal b2 = null;
  81. try {
  82. b1 = new BigDecimal(Func.parseStr(o1));
  83. } catch (Exception e) {
  84. b1 = new BigDecimal(0);
  85. }
  86. try {
  87. b2 = new BigDecimal(Func.parseStr(o2));
  88. } catch (Exception e) {
  89. b2 = new BigDecimal(0);
  90. }
  91. BigDecimal result = null;
  92. try {
  93. result = b1.add(b2);
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. }
  97. double douValue = 0d;
  98. if (result != null) {
  99. douValue = result.doubleValue();
  100. }
  101. return douValue;
  102. }
  103. public static BigDecimal add(BigDecimal b1, BigDecimal b2) {
  104. if (b1 == null) {
  105. b1 = new BigDecimal(0);
  106. }
  107. if (b2 == null) {
  108. b2 = new BigDecimal(0);
  109. }
  110. BigDecimal result = null;
  111. try {
  112. result = b1.add(b2);
  113. } catch (Exception e) {
  114. e.printStackTrace();
  115. result = new BigDecimal(0);
  116. }
  117. return result;
  118. }
  119. /**
  120. * 检查用户数据数据长度是否在指定的范围内
  121. *
  122. * @param data
  123. * @param length
  124. * @return
  125. */
  126. public static boolean checkDataLength(Object data, int length) {
  127. String dataStr = Func.parseStr(data);
  128. if (dataStr.trim().length() > length) {
  129. return false;
  130. }
  131. return true;
  132. }
  133. /**
  134. * 判断两个double类型的数据是否相等
  135. *
  136. * @param arg1
  137. * @param arg2
  138. * @return
  139. */
  140. public static boolean checkDblEqule(double arg1, double arg2) {
  141. return Math.abs(arg1 - arg2) > Func.FLOAT_ZERO_VALUE;
  142. }
  143. /**
  144. * 检查浮点型数据是否为"0.0"值
  145. */
  146. public static boolean checkDblZero(double dblIn) {
  147. return dblIn < Func.FLOAT_ZERO_VALUE && dblIn > -Func.FLOAT_ZERO_VALUE;
  148. }
  149. /*
  150. * 判断是否为浮点数,包括double和float
  151. * @param str 传入的字符串
  152. * @return 是浮点数返回true,否则返回false
  153. */
  154. public static boolean checkDouble(String str) {
  155. // Pattern pattern = Pattern.compile("[0-9]*((\\.{1})[0-9]+)?");
  156. Pattern pattern = Pattern.compile("^([\\+]?[\\d]*|[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$");
  157. return pattern.matcher(str).matches();
  158. }
  159. /*
  160. * 判断是否为负整数
  161. * @param str 传入的字符串
  162. * @return 是整数返回true,否则返回false
  163. */
  164. public static boolean checkFuInteger(String str) {
  165. Pattern pattern = Pattern.compile("^[\\-]?[\\d]*$");
  166. return pattern.matcher(str).matches();
  167. }
  168. /*
  169. * 判断是否为整数
  170. * @param str 传入的字符串
  171. * @return 是整数返回true,否则返回false
  172. */
  173. public static boolean checkInteger(String str) {
  174. Pattern pattern = Pattern.compile("^[\\+]?[\\d]*$");
  175. return pattern.matcher(str).matches();
  176. }
  177. /**
  178. * 检测字符串是否为null或空字符串或“null”字符串
  179. *
  180. * @param str 需要检测的字符串
  181. * @return 如果字符串为null或空字串或trim()后为空字串:true;否则返回false
  182. */
  183. public static boolean checkNull(String str) {
  184. if (str == null || "null".equals(str) || "undefined".equals(str)) {
  185. return true;
  186. }
  187. return str.trim().length() <= 0;
  188. }
  189. public static boolean checkNullOrEmpty(Object str) {
  190. if (str == null) {
  191. return true;
  192. }
  193. String value = Func.parseStr(str);
  194. if (value.trim().toLowerCase().equals("null") || value.trim().toLowerCase().equals("undefined")) {
  195. return true;
  196. } else {
  197. return value.trim().length() <= 0;
  198. }
  199. }
  200. public static List<Map<String, Object>> copyMap(List<Map<String, Object>> target) {
  201. if (target == null) {
  202. return null;
  203. }
  204. List<Map<String, Object>> source = new ArrayList<Map<String, Object>>();
  205. for (Map<String, Object> map : target) {
  206. Map<String, Object> newMap = new HashMap<String, Object>();
  207. Func.copyMap(newMap, map);
  208. source.add(newMap);
  209. }
  210. return source;
  211. }
  212. public static void copyMap(Map<String, Object> target, Map<String, Object> source) {
  213. if (target == null || source == null || source.size() < 1) {
  214. return;
  215. }
  216. for (Entry<String, Object> entry : source.entrySet()) {
  217. target.put(entry.getKey(), entry.getValue());
  218. }
  219. }
  220. public static boolean deleteDirectory(String sPath) {
  221. // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
  222. if (!sPath.endsWith(File.separator)) {
  223. sPath = sPath + File.separator;
  224. }
  225. File dirFile = new File(sPath);
  226. // 如果dir对应的文件不存在,或者不是一个目录,则退出
  227. if (!dirFile.exists() || !dirFile.isDirectory()) {
  228. return false;
  229. }
  230. boolean flag = true;
  231. // 删除文件夹下的所有文件(包括子目录)
  232. File[] files = dirFile.listFiles();
  233. for (File file : files) {
  234. // 删除子文件
  235. if (file.isFile()) {
  236. flag = Func.deleteFile(file.getAbsolutePath());
  237. if (!flag) {
  238. break;
  239. }
  240. } // 删除子目录
  241. else {
  242. flag = Func.deleteDirectory(file.getAbsolutePath());
  243. if (!flag) {
  244. break;
  245. }
  246. }
  247. }
  248. if (!flag) {
  249. return false;
  250. }
  251. return dirFile.delete();
  252. }
  253. public static boolean deleteDirFile(String sPath) {
  254. // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
  255. if (!sPath.endsWith(File.separator)) {
  256. sPath = sPath + File.separator;
  257. }
  258. File dirFile = new File(sPath);
  259. // 如果dir对应的文件不存在,或者不是一个目录,则退出
  260. if (!dirFile.exists() || !dirFile.isDirectory()) {
  261. return false;
  262. }
  263. boolean flag = true;
  264. // 删除文件夹下的所有文件(包括子目录)
  265. File[] files = dirFile.listFiles();
  266. for (File file : files) {
  267. // 删除子文件
  268. if (file.isFile()) {
  269. flag = Func.deleteFile(file.getAbsolutePath());
  270. if (!flag) {
  271. break;
  272. }
  273. } // 删除子目录
  274. else {
  275. flag = Func.deleteDirectory(file.getAbsolutePath());
  276. if (!flag) {
  277. break;
  278. }
  279. }
  280. }
  281. if (!flag) {
  282. return false;
  283. }
  284. return true;
  285. }
  286. public static boolean deleteFile(String sPath) {
  287. boolean flag = false;
  288. File file = new File(sPath);
  289. // 路径为文件且不为空则进行删除
  290. if (file.isFile() && file.exists()) {
  291. flag = file.delete();
  292. }
  293. return flag;
  294. }
  295. /**
  296. * 将指定字符串,通过指定格式转换为日期对象.
  297. *
  298. * @param dateStr .
  299. */
  300. public static Date parseDate(String dateStr) {
  301. if (Func.checkNullOrEmpty(dateStr)) {
  302. return null;
  303. }
  304. try {
  305. return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
  306. } catch (ParseException e) {
  307. e.printStackTrace();
  308. }
  309. try {
  310. return new SimpleDateFormat("yyyy/MM/dd").parse(dateStr);
  311. } catch (ParseException e) {
  312. e.printStackTrace();
  313. }
  314. try {
  315. return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(dateStr);
  316. } catch (ParseException e) {
  317. try {
  318. SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
  319. return sdf.parse(dateStr);
  320. } catch (ParseException e1) {
  321. }
  322. }
  323. return null;
  324. }
  325. /**
  326. * 除法运算(准确计算精度)
  327. *
  328. * @param o1
  329. * @param o2
  330. * @return
  331. */
  332. public static double divide(Object o1, Object o2, int... len) {
  333. int i = 10; // 默认取两位
  334. if (len.length > 0) {
  335. i = len[0];
  336. }
  337. BigDecimal b1 = null;
  338. BigDecimal b2 = null;
  339. if (Func.checkNullOrEmpty(o1)) {
  340. b1 = new BigDecimal(0);
  341. } else {
  342. b1 = new BigDecimal(Func.parseStr(o1));
  343. }
  344. if (Func.checkNullOrEmpty(o2)) {
  345. return 0;
  346. // b2 = new BigDecimal(0);
  347. } else {
  348. b2 = new BigDecimal(Func.parseStr(o2));
  349. }
  350. if (b2.doubleValue() == 0.0) {
  351. return 0;
  352. }
  353. BigDecimal result = b1.divide(b2, i, BigDecimal.ROUND_HALF_UP);
  354. return result.doubleValue();
  355. }
  356. public static String formatData(Date date, String format) {
  357. if (date == null) {
  358. date = new Date();
  359. }
  360. if (Func.checkNullOrEmpty(format)) {
  361. format = "yyyy-MM-dd HH:mm:ss";
  362. }
  363. SimpleDateFormat sdf = new SimpleDateFormat(format);
  364. return sdf.format(date);
  365. }
  366. /**
  367. * 获取常量类常量列表
  368. *
  369. * @return
  370. */
  371. @SuppressWarnings("rawtypes")
  372. public static List<String> getConstFieldList(Class clasz) throws Exception {
  373. if (clasz == null) {
  374. return null;
  375. }
  376. Field[] field = clasz.getDeclaredFields();
  377. List<String> constStrList = new ArrayList<String>();
  378. // 获取常量字段
  379. for (Field element : field) {
  380. constStrList.add(element.get(null).toString());
  381. }
  382. return constStrList;
  383. }
  384. /**
  385. * 通过枚举值获取对应的枚举
  386. *
  387. * @param <E> 枚举泛型
  388. * @param enumType 枚举类型
  389. * @param convertValue 需要转换的值
  390. * @param defaultValue 转换失败的默认值
  391. * @return
  392. */
  393. public static <E extends Enum<E>> E getEnumByName(Class<E> enumType, Object convertValue, E defaultValue) {
  394. if (convertValue == null) {
  395. return defaultValue;
  396. }
  397. String convertStr = Func.parseStr(convertValue);
  398. // 遍历枚举类型名称集合
  399. for (E item : EnumSet.allOf(enumType)) {
  400. if (item.name().equals(convertStr)) {
  401. return item;
  402. }
  403. }
  404. return defaultValue;
  405. }
  406. /**
  407. * 获取文件对应无后缀的文件名称
  408. *
  409. * @param fileName
  410. * @return
  411. */
  412. public static String getFileExtName(String fileName) {
  413. if (Func.checkNullOrEmpty(fileName)) {
  414. return "";
  415. }
  416. String fileExtName = "";
  417. if (fileName.lastIndexOf(".") >= 0) {
  418. fileExtName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
  419. }
  420. return fileExtName;
  421. }
  422. /**
  423. * 获取文件对应无后缀的文件名称
  424. *
  425. * @param file
  426. * @return
  427. */
  428. public static String getFileName(File file) {
  429. if (file == null) {
  430. return "";
  431. }
  432. String fileName = "";
  433. if (file.getName().lastIndexOf(".") >= 0) {
  434. fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
  435. } else {
  436. fileName = file.getName();
  437. }
  438. return fileName;
  439. }
  440. @SuppressWarnings("rawtypes")
  441. public static String getListSplitSqlStr(List list, String split) {
  442. if (list == null || Func.checkNullOrEmpty(split)) {
  443. return "";
  444. }
  445. StringBuffer strBuff = new StringBuffer();
  446. for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
  447. String str = (String) iterator.next();
  448. if (strBuff.length() > 0) {
  449. strBuff.append(new StringBuilder(String.valueOf(split)).append("'").append(str).append("'").toString());
  450. } else {
  451. strBuff.append(new StringBuilder("'").append(str).append("'").toString());
  452. }
  453. }
  454. return strBuff.toString();
  455. }
  456. @SuppressWarnings("rawtypes")
  457. public static String getListSplitStr(List list, String split) {
  458. if (list == null || Func.checkNullOrEmpty(split)) {
  459. return "";
  460. }
  461. StringBuffer strBuff = new StringBuffer();
  462. for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
  463. String str = (String) iterator.next();
  464. if (strBuff.length() > 0) {
  465. strBuff.append(new StringBuilder(String.valueOf(split)).append(str).toString());
  466. } else {
  467. strBuff.append(str);
  468. }
  469. }
  470. return strBuff.toString();
  471. }
  472. public static String getProjectFilePath(String str) throws Exception {
  473. URL url = Func.class.getClassLoader().getResource("");
  474. String path = url.getPath();
  475. path = path.substring(0, path.indexOf("WEB-INF")) + str + "/";
  476. File file = new File(path);
  477. if (!file.exists()) {
  478. file.mkdir();
  479. }
  480. return path;
  481. }
  482. /**
  483. * 正则表达式,匹配正负数
  484. *
  485. * @param str
  486. * @return
  487. */
  488. public static boolean matches(String str) {
  489. return str.matches(Func.PATTERN);
  490. }
  491. /**
  492. * 正则表达式,匹配正负数,小数点 ps:小数位长度小于等于2位
  493. *
  494. * @param str
  495. * @return
  496. */
  497. public static boolean matchesDot2(String str) {
  498. return str.matches(Func.PATTERN_DOT_2);
  499. }
  500. /**
  501. * 正则表达式,匹配正负数,小数点 ps:小数位长度小于等于3位
  502. *
  503. * @param str
  504. * @return
  505. */
  506. public static boolean matchesDot3(String str) {
  507. return str.matches(Func.PATTERN_DOT_3);
  508. }
  509. /**
  510. * 匹配数字和小数点,最多达到1.1.1.1.1.1级别
  511. *
  512. * @param value
  513. * @return
  514. */
  515. public static boolean matchesNumDot(String value) {
  516. if (Func.checkNullOrEmpty(value)) {
  517. return false;
  518. }
  519. return value.matches(Func.PATTERN_NUMDOT);
  520. }
  521. /**
  522. * 乘法运算(准确计算精度)
  523. *
  524. * @param o1
  525. * @param o2
  526. * @return
  527. */
  528. public static double multiply(Object o1, Object o2) {
  529. if (Func.checkNullOrEmpty(Func.parseStr(o1)) || Func.checkNullOrEmpty(Func.parseStr(o2))) {
  530. return 0;
  531. }
  532. BigDecimal b1 = new BigDecimal(Func.parseStr(o1));
  533. BigDecimal b2 = new BigDecimal(Func.parseStr(o2));
  534. BigDecimal result = b1.multiply(b2);
  535. if (result != null) {
  536. return result.doubleValue();
  537. }
  538. return 0;
  539. }
  540. /**
  541. * 已废弃,建议使用this.getClassUUID();
  542. */
  543. public static String newGuid() {
  544. return UUID.randomUUID().toString();
  545. }
  546. public static boolean parseBoolean(Object objIn) {
  547. return Func.parseBoolean(objIn, false);
  548. }
  549. public static boolean parseBoolean(Object objIn, boolean defaultValue) {
  550. boolean bRe = defaultValue;
  551. if (objIn == null) {
  552. return bRe;
  553. }
  554. try {
  555. bRe = Boolean.parseBoolean(Func.parseStr(objIn));
  556. } catch (Exception exception) {
  557. }
  558. return bRe;
  559. }
  560. public static double parseDbl(Object objIn) {
  561. double dbl = 0.0D;
  562. if (objIn == null) {
  563. return dbl;
  564. }
  565. try {
  566. dbl = Double.parseDouble(Func.parseStr(objIn));
  567. } catch (Exception exception) {
  568. }
  569. return dbl;
  570. }
  571. /**
  572. * 解析浮点型字符串(对应值为零则返回空)
  573. */
  574. public static String parseDblStr(Object objIn, int carryNum) {
  575. // 当为0的时候显示为空
  576. if (Func.parseDbl(objIn) == 0.0D) {
  577. return "";
  578. }
  579. return Func.setScale(objIn, carryNum);
  580. // Double dbl = Func.parseDbl(objIn);
  581. // if (CommFunc.CheckDblZero(dbl)) return "";
  582. //
  583. // // 进行精度处理
  584. // DecimalFormat decFormat = new DecimalFormat();
  585. // decFormat.setMinimumFractionDigits(carryNum);
  586. // decFormat.setMaximumFractionDigits(carryNum);
  587. // return decFormat.format(dbl);
  588. }
  589. /**
  590. * 解析浮点型字符串(对应值为零则返回空)
  591. */
  592. public static String parseDblStr(Object objIn, int carryNum, boolean bDisplayZero) {
  593. double dbl = Func.round(objIn, carryNum);
  594. if (!bDisplayZero && Func.checkDblZero(dbl)) {
  595. return "";
  596. }
  597. // 进行精度处理
  598. DecimalFormat decFormat = new DecimalFormat();
  599. decFormat.setMinimumFractionDigits(carryNum);
  600. decFormat.setMaximumFractionDigits(carryNum);
  601. if (carryNum == 2) {
  602. decFormat.applyPattern("0.00");
  603. } else {
  604. decFormat.applyPattern("#.#");
  605. }
  606. return decFormat.format(dbl);
  607. }
  608. public static float parseFloat(Object objIn) {
  609. float flt = 0.0F;
  610. if (objIn == null) {
  611. return flt;
  612. }
  613. try {
  614. flt = Float.parseFloat(Func.parseStr(objIn));
  615. } catch (Exception exception) {
  616. }
  617. return flt;
  618. }
  619. public static int parseInt(Object objIn) {
  620. return (int) Func.parseDbl(objIn);
  621. }
  622. public static long parseLong(Object objIn) {
  623. return (long) Func.parseDbl(objIn);
  624. }
  625. public static String parseStr(Object objIn) {
  626. if (objIn == null) {
  627. return "";
  628. } else {
  629. return objIn.toString().trim();
  630. }
  631. }
  632. /**
  633. * 检验手机号码格式
  634. * @param phone
  635. * @return
  636. */
  637. public static boolean checkPhone(String phone) {
  638. String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
  639. if (checkNull(phone))
  640. return false;
  641. if (phone.length() != 11)
  642. return false;
  643. Pattern p = Pattern.compile(regex);
  644. Matcher m = p.matcher(phone);
  645. return m.matches();
  646. }
  647. /**
  648. * 验证身份证真假
  649. * @param carNumber 身份证号
  650. * @return boolean*/
  651. public static boolean isCard(String carNumber) {
  652. //判断输入身份证号长度是否合法
  653. if (carNumber.length() != 18) {
  654. // throw new RuntimeException("身份证长度不合法");//不合法 抛出一个异常
  655. return false;
  656. }
  657. //校验身份证真假
  658. int sum = 0;
  659. int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//将加权因子定义为数组
  660. //遍历weight数组 求身份证前17项系数和
  661. for (int i = 0; i < weight.length; i++) {
  662. int n = carNumber.charAt(i) - 48;//获取 身份证对应数
  663. int w = weight[i];
  664. sum += w * n;
  665. }
  666. //对11求余
  667. int index = sum % 11;
  668. //校验码
  669. String m = "10X98765432";
  670. //获取身份证最后一位进行比对
  671. return m.charAt(index) == carNumber.charAt(17);
  672. }
  673. /**
  674. * 判断code编码是否在startCode和endCode之间
  675. *
  676. * @param code
  677. * @param startCode
  678. * @param endCode
  679. * @return
  680. */
  681. public static boolean rangeParse(String code, String startCode, String endCode) {
  682. int a = startCode.compareToIgnoreCase(code);
  683. int b = endCode.compareToIgnoreCase(code);
  684. if (a < 0 && b < 0 || a > 0 && b > 0) {
  685. return false;
  686. }
  687. return true;
  688. }
  689. /**
  690. * 字符串转译
  691. *
  692. * @param source
  693. * @return
  694. */
  695. public static String replaceAllTsStr(String source) {
  696. // 替换掉空格,中文的字符转换成对应的英文字符
  697. source = source.replaceAll(" ", "").replaceAll("(", "(").replaceAll(")", ")").replaceAll("\n", "");
  698. return source;
  699. }
  700. public static String replaceAllTsStr2(String source) {
  701. source = source.replaceAll("\\[", "").replaceAll("【", "").replaceAll("\\]", "").replaceAll("】", "");
  702. return source;
  703. }
  704. /**
  705. * 四舍五入运算
  706. *
  707. * @param o1
  708. * @param round
  709. * @return
  710. */
  711. public static double round(Object o1, int... round) {
  712. int len = 2; // 默认取两位
  713. double v = 1;
  714. if (round.length > 0) {
  715. len = round[0];
  716. }
  717. for (int i = 0; i < len; i++) {
  718. v *= 10;
  719. }
  720. BigDecimal b = new BigDecimal(Func.parseStr(o1));
  721. BigDecimal val = new BigDecimal(v);
  722. BigDecimal result = b.multiply(val).divide(val, len, BigDecimal.ROUND_HALF_UP);
  723. return result.doubleValue();
  724. }
  725. /**
  726. * 设置数值小数位数
  727. *
  728. * @param dbl
  729. * @param carryNum
  730. * @return
  731. */
  732. public static double setDoubleScale(double dbl, int carryNum) {
  733. if (carryNum < 0) {
  734. return dbl;
  735. }
  736. return BigDecimal.valueOf(dbl).setScale(carryNum, BigDecimal.ROUND_HALF_UP).doubleValue();
  737. }
  738. /**
  739. * 设置小数位数
  740. *
  741. * @param data 需要转换的数据
  742. * @param round 有效小数位数(默认为两位)
  743. * @return
  744. */
  745. public static String setScale(Object data, int... round) {
  746. // // 当为0的时候显示为空
  747. // if (Func.parseDbl(data) == 0.0D)
  748. // {
  749. // return "";
  750. // }
  751. double re = 0d;
  752. try {
  753. re = Func.parseDbl(data);
  754. } catch (Exception e) {
  755. return Func.parseStr(data);
  756. }
  757. if (re == 0d) {
  758. return "0";
  759. }
  760. if (round.length <= 0) {
  761. round = new int[]
  762. {2}; // 默认取两位小数
  763. }
  764. try {
  765. return Func.df.format(BigDecimal.valueOf(re).setScale(round[0], BigDecimal.ROUND_HALF_UP));
  766. } catch (Exception e) {
  767. }
  768. return "";
  769. }
  770. /**
  771. * 过滤掉特殊字符
  772. *
  773. * @param str
  774. * @return
  775. */
  776. public static String stringFilter(String str) {
  777. if (Func.checkNullOrEmpty(str)) {
  778. return str;
  779. }
  780. // 只允许字母和数字
  781. // String regEx = "[^a-zA-Z0-9]";
  782. // 清除掉所有特殊字符
  783. String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
  784. Pattern p = Pattern.compile(regEx);
  785. Matcher m = p.matcher(str);
  786. return m.replaceAll("").trim();
  787. }
  788. /**
  789. * 减法运算(准确计算精度)
  790. *
  791. * @param o1
  792. * @param o2
  793. * @return
  794. */
  795. public static double subtract(Object o1, Object o2) {
  796. BigDecimal b1 = null;
  797. BigDecimal b2 = null;
  798. try {
  799. b1 = new BigDecimal(Func.parseStr(o1));
  800. } catch (Exception e) {
  801. b1 = new BigDecimal(0);
  802. }
  803. try {
  804. b2 = new BigDecimal(Func.parseStr(o2));
  805. } catch (Exception e) {
  806. b2 = new BigDecimal(0);
  807. }
  808. BigDecimal result = null;
  809. try {
  810. result = b1.subtract(b2);
  811. } catch (Exception e) {
  812. e.printStackTrace();
  813. }
  814. double douValue = 0d;
  815. if (result != null) {
  816. douValue = result.doubleValue();
  817. }
  818. return douValue;
  819. }
  820. /**
  821. * 将传入的Params的filter字符串转换成json字符串
  822. *
  823. * @param filter 例: usrid=1,name=myname,code=123
  824. * @return
  825. */
  826. @SuppressWarnings(
  827. {"rawtypes", "unchecked"})
  828. public static Map<String, String> transferJsonToMap(String filter, String splitStr) {
  829. Map map = new HashMap<String, String>();
  830. // 根据“&”切割,获取各属性名称及值
  831. String[] items = filter.split(splitStr);
  832. if (items.length <= 0) {
  833. return map;
  834. }
  835. for (String tmpStr : items) {
  836. // 根据“=”切割,划分名称与值
  837. String[] tmpItem = tmpStr.split("=");
  838. if (tmpItem.length <= 1) {
  839. continue;
  840. }
  841. // 加入map
  842. map.put(tmpItem[0], tmpItem[1]);
  843. }
  844. return map;
  845. }
  846. /**
  847. * 将传入的Params的filter字符串转换成json字符串
  848. *
  849. * @param filter 例: usrid=1&name=myname&code=123
  850. * @return {userid:1,name:myname,code:123}
  851. */
  852. public static String transferToJson(String filter) {
  853. // 根据“&”切割,获取各属性名称及值
  854. String[] items = filter.split("&");
  855. if (items.length <= 0) {
  856. return "{}";
  857. }
  858. StringBuffer buffer = new StringBuffer();
  859. buffer.append("{");
  860. for (String tmpStr : items) {
  861. // 根据“=”切割,划分名称与值
  862. String[] tmpItem = tmpStr.split("=");
  863. if (tmpItem.length <= 1) {
  864. continue;
  865. }
  866. // 构造json
  867. buffer.append("\"" + tmpItem[0] + "\":" + "\"" + tmpItem[1] + "\",");
  868. }
  869. String json = buffer.toString();
  870. // 去除最后的",",并加上"}"
  871. if (json.lastIndexOf(",") == json.length() - 1) {
  872. json = json.substring(0, json.length() - 1) + "}";
  873. } else {
  874. json += "}";
  875. }
  876. return json;
  877. }
  878. /**
  879. * 尝试转换Double值数据
  880. *
  881. * @param parseObject
  882. * @return
  883. */
  884. public static double tryParseDouble(String parseObject) {
  885. double parseValue = Double.MIN_VALUE;
  886. if (parseObject == null) {
  887. return parseValue;
  888. }
  889. try {
  890. // 尝试转换值
  891. parseValue = Double.valueOf(parseObject);
  892. return parseValue;
  893. } catch (Exception e) {
  894. return parseValue;
  895. }
  896. }
  897. public static String getFirstImage(String image) {
  898. try {
  899. if (Func.checkNullOrEmpty(image)) {
  900. return image;
  901. }
  902. String[] is = image.split(",");
  903. if (is == null || is.length < 1) {
  904. return image;
  905. }
  906. return is[0];
  907. } catch (Exception e) {
  908. e.printStackTrace();
  909. }
  910. return image;
  911. }
  912. public static String convertCodeUtf8(String value) {
  913. try {
  914. if (checkNullOrEmpty(value)) {
  915. return "";
  916. }
  917. return new String(parseStr(value).getBytes("ISO-8859-1"), "UTF-8");
  918. } catch (Exception e) {
  919. return "";
  920. }
  921. }
  922. /**
  923. * 将set转化成数组
  924. *
  925. * @param set set集合
  926. * @return 返回数组
  927. */
  928. public static String[] setToArray(Set<String> set) {
  929. if (set == null || set.isEmpty())
  930. return new String[0];
  931. String[] strArray = new String[set.size()];
  932. Object[] obj = set.toArray();
  933. for (int i = 0; i < obj.length; i++) {
  934. strArray[i] = parseStr(obj[i]);
  935. }
  936. return strArray;
  937. }
  938. /**
  939. * 将set转化成数组
  940. *
  941. * @param list set集合
  942. * @return 返回数组
  943. */
  944. public static String[] listToArray(List<String> list) {
  945. if (list == null || list.isEmpty())
  946. return null;
  947. String[] strArray = new String[list.size()];
  948. Object[] obj = list.toArray();
  949. for (int i = 0; i < obj.length; i++) {
  950. strArray[i] = parseStr(obj[i]);
  951. }
  952. return strArray;
  953. }
  954. /**
  955. * 通过",",进行转换, 将数组对象转化成list集合对象,
  956. *
  957. * @param param
  958. * @return
  959. */
  960. public static List<String> strToList(String param) {
  961. String paramData = param.replace(",", ",");
  962. return strToListBySeparator(paramData, ",");
  963. }
  964. /**
  965. * 通过separator,进行转换, 将数组对象转化成list集合对象
  966. *
  967. * @param param
  968. * @return
  969. */
  970. public static List<String> strToListBySeparator(String param, String separator) {
  971. if (checkNullOrEmpty(param) || checkNullOrEmpty(separator)) {
  972. return new ArrayList<String>();
  973. }
  974. return arrayToList(param.split(separator));
  975. }
  976. /**
  977. * 将数组转化成List
  978. *
  979. * @param array 数组
  980. * @return
  981. */
  982. public static List<String> arrayToList(String[] array) {
  983. if (array == null || array.length <= 0) {
  984. return new ArrayList<String>();
  985. }
  986. List<String> result = new ArrayList<String>();
  987. for (String str : array) {
  988. if (checkNullOrEmpty(str)) {
  989. continue;
  990. }
  991. result.add(parseStr(str));
  992. }
  993. return result;
  994. }
  995. /**
  996. * 判断当前数据是否是数字
  997. *
  998. * @param obj 传入数据
  999. * @return
  1000. */
  1001. public static boolean isNumeric(Object obj) {
  1002. String str = parseStr(obj);
  1003. try {
  1004. Double.parseDouble(str);
  1005. return true;
  1006. } catch (Exception e) {
  1007. }
  1008. return false;
  1009. }
  1010. /**
  1011. * 将ids转化成set集合“,”
  1012. *
  1013. * @param ids
  1014. * @return
  1015. */
  1016. public static Set<String> idsSet(String ids) {
  1017. if (Func.checkNull(ids))
  1018. return new HashSet<String>();
  1019. Set<String> set = new HashSet<String>();
  1020. String[] idsArr = ids.split(",");
  1021. for (int i = 0; i < idsArr.length; i++) {
  1022. if (Func.checkNullOrEmpty(idsArr[i]))
  1023. continue;
  1024. set.add(Func.parseStr(idsArr[i]));
  1025. }
  1026. return set;
  1027. }
  1028. /**
  1029. * 将别名字符串转化成set集合“,”
  1030. *
  1031. * @param aliaseName
  1032. * @return
  1033. */
  1034. public static Set<String> strToSet(String aliaseName) {
  1035. if (Func.checkNull(aliaseName))
  1036. return new HashSet<String>();
  1037. Set<String> set = new HashSet<String>();
  1038. String[] aliasArr = aliaseName.split(";");
  1039. for (int i = 0; i < aliasArr.length; i++) {
  1040. if (Func.checkNullOrEmpty(aliasArr[i]))
  1041. continue;
  1042. set.add(Func.parseStr(aliasArr[i]));
  1043. }
  1044. return set;
  1045. }
  1046. /**
  1047. * 动态识别单位
  1048. *
  1049. * @param dwMap
  1050. * @param dw
  1051. * @return
  1052. */
  1053. public static String dynamicRecognition(Map<String, String> dwMap, String dw) {
  1054. if (dwMap == null || dwMap.isEmpty() || Func.checkNullOrEmpty(dw))
  1055. return null;
  1056. if (dwMap.containsKey(dw))
  1057. return dw;
  1058. String aliaseName = null;
  1059. Set<String> aliaseSetName = new HashSet<String>();
  1060. for (Entry<String, String> entry : dwMap.entrySet()) {
  1061. aliaseName = entry.getValue();
  1062. if (Func.checkNullOrEmpty(aliaseName))
  1063. continue;
  1064. aliaseSetName = Func.strToSet(aliaseName);
  1065. if (aliaseSetName.contains(dw))
  1066. return Func.parseStr(entry.getKey());
  1067. }
  1068. return "";
  1069. }
  1070. /**
  1071. * 获取一个8位的UUID值
  1072. *
  1073. * @return
  1074. */
  1075. public static String get8UUID() {
  1076. UUID id = UUID.randomUUID();
  1077. String[] idd = id.toString().split("-");
  1078. return idd[0];
  1079. }
  1080. public static String replaceSpecChar(Object v) {
  1081. String str = Func.parseStr(v);
  1082. if (!Func.checkNullOrEmpty(str)) {
  1083. return str.replaceAll(":", ":").replaceAll("(", "(").replaceAll(")", ")").replaceAll(";", ";")
  1084. .replaceAll("。", ".").replaceAll("?", "?").replaceAll("!", "!").replaceAll("×", "*")
  1085. .replaceAll("“", "\"").replaceAll("”", "\"").replaceAll("吨", "t").replaceAll("Km", "km")
  1086. .replaceAll(",", ",").replaceAll("千伏", "kV").replaceAll("千米", "km").replaceAll("米", "m")
  1087. .replaceAll("M", "m").replaceAll("KM", "km").replaceAll("kM", "km").replaceAll("m²", "m2")
  1088. .replaceAll("mm²", "mm2").replaceAll("mm³", "mm3").replaceAll("m³", "m3");
  1089. }
  1090. return str;
  1091. }
  1092. /**
  1093. * 进行数字兼容
  1094. *
  1095. * @param dydj
  1096. * @return
  1097. */
  1098. public static String compatibleVoltage(String dydj) {
  1099. if (checkNullOrEmpty(dydj))
  1100. return "";
  1101. if (dydj.contains("35")) {
  1102. return "35kV";
  1103. } else if (dydj.contains("110")) {
  1104. return "110kV";
  1105. } else if (dydj.contains("220")) {
  1106. return "220kV";
  1107. } else if (dydj.contains("500")) {
  1108. return "500kV";
  1109. } else if (dydj.contains("10")) {
  1110. return "10kV";
  1111. }
  1112. return "";
  1113. }
  1114. public static String replaceQuantities(Object v) {
  1115. String str = Func.parseStr(v);
  1116. if (!Func.checkNullOrEmpty(str)) {
  1117. return str.replaceAll(":", ":").replaceAll("(", "(").replaceAll(")", ")").replaceAll(";", ";")
  1118. .replaceAll("。", ".").replaceAll("?", "?").replaceAll("!", "!").replaceAll("“", "\"")
  1119. .replaceAll("”", "\"").replaceAll("吨", "t").replaceAll("Km", "km").replaceAll("KM", "km")
  1120. .replaceAll("kM", "km").replaceAll(",", ",").replaceAll("\n", "").replaceAll("\r", "")
  1121. .replaceAll("千伏", "kV").replaceAll("Kv", "kV").replaceAll("KV", "kV").replaceAll("千米", "km")
  1122. .replaceAll("米", "m").replaceAll("M", "m").replaceAll("m²", "m2").replaceAll("mm²", "mm2")
  1123. .replaceAll("mm³", "mm3").replaceAll("m³", "m3");
  1124. }
  1125. return str;
  1126. }
  1127. /**
  1128. * 通过",",进行转换, 将数组对象转化成list集合对象,并将每一个值添加进一个list中
  1129. *
  1130. * @param result
  1131. * @return
  1132. */
  1133. public static void strIntoList(String param, List<String> result) {
  1134. if (checkNullOrEmpty(param))
  1135. return;
  1136. String[] array = param.split(",");
  1137. if (array == null || array.length <= 0)
  1138. return;
  1139. for (String str : array) {
  1140. if (checkNullOrEmpty(str))
  1141. continue;
  1142. result.add(str);
  1143. }
  1144. }
  1145. /**
  1146. * 通过",",进行转换, 将数组对象转化成list集合对象,并将每一个值添加进一个list中
  1147. *
  1148. * @param result
  1149. * @return
  1150. */
  1151. public static void strIntoSet(String param, Set<String> result) {
  1152. if (checkNullOrEmpty(param))
  1153. return;
  1154. String[] array = param.split(",");
  1155. if (array == null || array.length <= 0)
  1156. return;
  1157. for (String str : array) {
  1158. if (checkNullOrEmpty(str))
  1159. continue;
  1160. result.add(str);
  1161. }
  1162. }
  1163. /**
  1164. * 符号转换, 中英文之间符号转换
  1165. *
  1166. * @param str
  1167. * @return
  1168. */
  1169. public static String singleConvert(String str) {
  1170. if (checkNullOrEmpty(str)) {
  1171. return null;
  1172. }
  1173. if (str.equals(",")) {
  1174. return ",";
  1175. } else if (str.equals(",")) {
  1176. return ",";
  1177. } else if (str.equals(".")) {
  1178. return "。";
  1179. } else if (str.equals("。")) {
  1180. return ".";
  1181. } else if (str.equals("、")) {
  1182. return "、";
  1183. }
  1184. return null;
  1185. }
  1186. /**
  1187. * 替换字符串中的制表、换行等符号。
  1188. */
  1189. public static String replaceBlank(String str) {
  1190. String dest = "";
  1191. if (str != null) {
  1192. Pattern p = Pattern.compile("\\s*|\t|\r|\n");
  1193. Matcher m = p.matcher(str);
  1194. dest = m.replaceAll("");
  1195. }
  1196. return dest;
  1197. }
  1198. /**
  1199. * 替换字符串中的制表、换行等符号。
  1200. */
  1201. public static String replaceSpecBlank(String str) {
  1202. String dest = "";
  1203. if (str != null) {
  1204. Pattern p = Pattern.compile("\\t|\n");
  1205. Matcher m = p.matcher(str);
  1206. dest = m.replaceAll("");
  1207. }
  1208. return dest;
  1209. }
  1210. /**
  1211. * Map转成实体对象
  1212. *
  1213. * @param map map实体对象包含属性
  1214. * @param clazz 实体对象类型
  1215. * @return
  1216. */
  1217. public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
  1218. if (map == null) {
  1219. return null;
  1220. }
  1221. Object obj = null;
  1222. try {
  1223. obj = clazz.newInstance();
  1224. Field[] fields = obj.getClass().getDeclaredFields();
  1225. for (Field field : fields) {
  1226. int mod = field.getModifiers();
  1227. if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
  1228. continue;
  1229. }
  1230. field.setAccessible(true);
  1231. String flag = parseStr(map.get(field.getName()));
  1232. if (!Func.checkNullOrEmpty(flag)) {
  1233. field.set(obj, flag);
  1234. }
  1235. }
  1236. } catch (Exception e) {
  1237. e.printStackTrace();
  1238. }
  1239. return obj;
  1240. }
  1241. }