package com.yqzx.generator.util; import cn.hutool.core.util.StrUtil; import java.net.URISyntaxException; import java.util.Arrays; /** * @description: 工具类 * @author: chaoyapeng * @time: 2020/8/18 16:32 */ public class ToolUtil { /** * 首字母变大写 */ public static String firstLetterToUpper(String str) { char firstChar = str.charAt(0); if (firstChar >= 'a' && firstChar <= 'z') { char[] arr = str.toCharArray(); arr[0] -= ('a' - 'A'); return new String(arr); } return str; } /** * 格式化文本 * * @param template 文本模板,被替换的部分用 {} 表示 * @param values 参数值 * @return 格式化后的文本 */ /** * 格式化文本, {} 表示占位符
* 例如:format("aaa {} ccc", "bbb") ----> aaa bbb ccc * * @param template 文本模板,被替换的部分用 {} 表示 * @param values 参数值 * @return 格式化后的文本 */ public static String format(String template, Object... values) { if (values == null || values.length == 0) { return template; } final StringBuilder sb = new StringBuilder(); final int length = template.length(); int valueIndex = 0; char currentChar; for (int i = 0; i < length; i++) { if (valueIndex >= values.length) { sb.append(sub(template, i, length)); break; } currentChar = template.charAt(i); if (currentChar == '{') { final char nextChar = template.charAt(++i); if (nextChar == '}') { sb.append(values[valueIndex++]); } else { sb.append('{').append(nextChar); } } else { sb.append(currentChar); } } return sb.toString(); } /** * 改进JDK subString
* index从0开始计算,最后一个字符为-1
* 如果from和to位置一样,返回 ""
* 如果from或to为负数,则按照length从后向前数位置,如果绝对值大于字符串长度,则from归到0,to归到length
* 如果经过修正的index中from大于to,则互换from和to * example:
* abcdefgh 2 3 -> c
* abcdefgh 2 -3 -> cde
* * @param string String * @param fromIndex 开始的index(包括) * @param toIndex 结束的index(不包括) * @return 字串 */ public static String sub(String string, int fromIndex, int toIndex) { int len = string.length(); if (fromIndex < 0) { fromIndex = len + fromIndex; if(fromIndex < 0 ) { fromIndex = 0; } } else if(fromIndex >= len) { fromIndex = len -1; } if (toIndex < 0) { toIndex = len + toIndex; if(toIndex < 0) { toIndex = len; } } else if(toIndex > len) { toIndex = len; } if (toIndex < fromIndex) { int tmp = fromIndex; fromIndex = toIndex; toIndex = tmp; } if (fromIndex == toIndex) { return ""; } char[] strArray = string.toCharArray(); char[] newStrArray = Arrays.copyOfRange(strArray, fromIndex, toIndex); return new String(newStrArray); } /** * 获取项目路径 * @param filePath * @return */ public static String getWebRootPath(String filePath) { try { String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath(); path = path.replace("/target/classes/", ""); path = path.replace("file:/", ""); if (StrUtil.isEmpty(filePath)) { return path; } else { return path + "/" + filePath; } } catch (URISyntaxException e) { throw new RuntimeException(e); } } }