/字符串工具类/
StringUtils
public class StringUtils extends org.apache.commons.lang.StringUtils{
public static DecimalFormat dfmt = new DecimalFormat("0");
public static final String UTF_8 = "UTF-8";
private static Gson gson,gson2;
//这个是干什么的,digits:位
private static String digits(long val ,int digits){
long hi = 1L << (digits * 4);
//将长整型数值转换为指定的进制数(最大支持62禁止,字母数字已经用尽,详见Numbers.java)
return Numbers.toString( hi | (val &(hi-1)), Numbers.MAX_RADIX).substring(1);
}
//1:获取UUID12
public static String getUUID12(){
String s = getUUID();
return s.substring(0,12);
}
//2:以62进制(数字+字母)生成19位UUID,最短的UUID
public static String getUUID19(){
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder();
sb.append( digits(uuid.getMostSignificantBits() >> 32,8) );
sb.append( digits(uuid.getMostSignificantBits() >> 16,4) );
sb.append( digits(uuid.getMostSignificantBits() ,4) );
sb.append( digits(uuid.getMostSignificantBits() >> 48,4) );
sb.append( digits(uuid.getMostSignificantBits() ,12) );
return sb.toString();
}
//3.去掉UUID中的"-"
public static String getUUID(){
return UUID.randomUUID().toString.replace("-","");
}
//4:获取一个gson工具示例 disableHtmlEscaping:禁用html转义
public static Gson getGson(boolean...disableHtmlEscaping){
if( gson == null && gson2 == null ){
gson = new Gson();
gson2 = new GsonBuilder().disableHtmlEscaping().create();
}
return disableHtmlEscaping.length > 0 && disableHtmlEscaping[0] ? gson2 : gson ;
}
//5:转换Byte,Short ,Integer ,Long, Float ,Doubel包装类型,写法都一样,还有BigDecimal,Boolean
public static Byte parseByte(Object str){
return str == null ? 0: Byte.valueOf( isNumberic(str.toString()) ? Byte.parseByte(str.toString()) : 0) ;
}
public static Short parseShort(Object str){
return str == null ? 0: Short.valueOf( isNumberic(str.toString()) ? Byte.parseShort(str.toString()) : 0) ;
}
public static Integer parseInt(Object str){
return str == null ? 0: Integer.valueOf( isNumberic(str.toString()) ? Integer.parseInt(str.toString()) : 0) ;
}
...
//转换BigDecimal,保留精度。空就转换“0.00”
public static BigDecimal parseDecimal(Object str){
return new BigDecimal( StringUtils.defaultIfEmpty(StringUtils.null2Blank(str),"0.00") );
}
//y,yes,t,true,1 这些字符串都 解析为 true(Boolean)
public static Boolean parseBoolean(Object str){
if(str == null ) return false;
String s = str.toString().toLowerCase();
if( (“y”.equalsIgnoreCase(s) ) || ("yes".equalsIgnoreCase(s) ) || ("true".equalsIgnoreCase(s))|| (“t”.equalsIgnoreCase(s))|| ("1".equalsIgnoreCase(s) ) {
return true;
}
return false;
}
//6:null 或者“null” 转换为“”
public static final String null2Blank(Object str){
return (null == str || "null".equlas(str)) ? "" : str.toString() ;
}
//7:判断字符串是否为数字型字符串
public static boolean inNumberic(String str){
Mather isNum = Pattern.compile( "(-|\\+)?[0-9]+(.[0-9]+)?").matcher(str) ;
return isNum.matches();
}
//8:数字格式化: (234.23, 5)---234.23000 ("0",5)---0.00000 ("NaN", 5)--0.00000
public static String fmtNumber(Object obj, int scale) throws Exception{
//空值格式化
String objStr = defaultIfEmpty(null2Blank(obj),"0");
objStr = "NaN".equals(objStr)?"0" : objStr;
double doubleValue = new BigDecimal( Double.valueOf(objStr).doubleValue() )
.setScale(scale, BigDecimal.ROUND_HALF_EVEN)
.doubleValue() ;
StringBuffer endWith = new StringBuffer();
for( int i=0; i<scale;i++ ){endWith .append("0");}
String pattern = "0";
if(endWith.length() > 0){
pattern = pattern.concat(".").concat(endWith.toString() ); //scale=5, pattern=0.00000
}
dfmt.applyPattern(pattern);
return dfmt.format(doubleValue);
}
//9:改成html编码 (比如:&取代 &(html转义符))--不知道哪儿会用到
public static String htmlEncode(String txt){
if(null != txt ){
txt = txt.replace("&","&").replace(""e;","\"").replace(">",">").replace("<","<").replace(" "," ");
}
return txt;
}
//10:去除html编码----不知道哪儿会用到
public static String htmlDecode(String txt){
if(null != txt ){
txt = txt.replace("&","&").replace("&amp;","&")
.replace("&quot;",""e;").replace("\"",""e;")
.replace("&gt;",">").replace(">",">")
.replace("&lt;","<").replace("<","<")
replace("&nbsp;"," ");
}
return txt;
}
//11:去除html&js ---不知道哪儿会用到
public static String replaceHtmlJs(String txt){
if(null != txt){
txt = txt.replaceAll("<[a-zA-Z]+[1-9]?[^><]*>", "").replaceAll("</[a-zA-Z]+[1-9]?>", "").replaceAll("eval\\((.*)\\)", "");
}
}
//12:针对数据库查询参数中的特殊字符(“ ‘ %)进行转义--我看不懂
public static String relaceSpecial(String txt){
if(null != txt){
txt = txt.replaceAll("\"","\\\\\"").replaceAll("'","\\\\'").replaceAll("%","\\\\%");
}
}
//13:base64编码,解码
public static String base64Encode(String txt ) throws Exception{
return new String(Base64.encodeBase64(source.getBytes(UTF_8)),UTF_8 );
}
public static String base64Decode(String txt ) throws Exception{
return new String(Base64.decodeBase64(source.getBytes(UTF_8)),UTF_8);
}
//14:半角,全角互转--完全不知道哪儿用得到
//全角转半角
public static String toDBC(String input){
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
return new String(c);
}
//半角转全角
public static String toSBC(String input){
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
c[i] = '\u3000'; //采用十六进制,相当于十进制的12288
} else if (c[i] < '\177') { //采用八进制,相当于十进制的127
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
//15:汉字相关 --汉子转pinyin
private final static int[] li_SecPosValue = { 1601, 1637, 1833, 2078, 2274, 2302, 2433,
2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027,4086, 4390, 4558, 4684, 4925, 5249, 5590 };
private final static String[] lc_FirstLetter = { "a", "b"', "c", "d", '"e", "f", "g", "h", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "w", "x", "y", "z" };
//15.获取给定[汉字]的首字母,即声母 "我" w "你们" n
public static String getFirstLetter(String chinese) throws Exception{
if( chinese == null || chinese.trim().length() == 0 ){return ""; }
chinese = new String (chinese.getBytes("GB2312"),"ISO8859-1");
if( chinese.length() > 1){
//判断是不是汉字
int li_SectorCode = (int)chinese.charAt(0); //汉字区码
int li_PositionCode = (int)chinese.charAt(1); //汉字位码
li_SectorCode = li_SectorCode -160;
li_PositionCode = li_PositionCode -160;
int li_SecPosCode = li_SectorCode * 100 + li_PositionCode ;//汉字区位码
if(li_SecPosCode > 1600 && li_SecPosCode <5590 ){
for( int i = 0 ; i< 23; i++){
if(li_SecPosCode >= li_SecPosCode[i] && li_SecPosCode <li_SecPosCode [i+1] ){
chinese = lc_FirstLetter [i];
break;
}
}
}else{//非汉字字符,如图形符号或ASCII码
chinese = new String (chinese.getBytes("ISO8859-1"),"GB2312");
chinese = chinese.substring(0,1);
}
}
//chinese.length()<=1.
return chinese;
}
//15.0使用pinyinHelper获取中文的首字母--"我们是中国人" -wmszgr
public static String getPinYinHeadChar(String str){
String convert = "";
for( int j = 0; j<str.length(); j++){
char word = str.chartAt(j); //获取每一个字符,汉字 '我' '们'
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if(pinyinArray != null ){ convert += pinyinArray[0].charAt(0);}
else{convert += word;}
}
return convert;
}
//15.1 将汉字转换为 全拼
public static String getPinYin(String src){
char[] cl_chars = src.trim().toCharArray();
String hanyupinyin = "";
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
try {
for (int i=0; i<cl_chars.length; i++){
if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")){// 如果字符是中文,则将中文转为汉语拼音
hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
} else {// 如果字符不是中文,则不转换
hanyupinyin += cl_chars[i];
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
System.out.println("字符不能转成汉语拼音");
}
return hanyupinyin;
}
public static String getpinyin
//15.2 将数字转换为大写
public static String numToUpper(int num){
String[] u = {"〇",“一”,“二”,“三”,“四”,“五”,“六”,“七”,“八”,“九”,“十”};
char[] str = String.valueOf(num).toCharArray();
String rstr = "";
//遍历字符数组
for(int i = 0;i < str.length; i++){
rstr = rstr +u[Integer.parseInt(str[i]+"")];//u[2] 二
}
return rstr;
}
//16,Json转换
public static String getJsonObjectStringVal(JsonObject obj, String name){
JsonElement e = obj.get(name);
System.out.println("--------------------------"+e);
return e == null ? "" : e.getAsString();
}
//17:判断字符串是否为空或者空字符串 (这里空格 不算空字符串)
public static boolean isNotNullOrEmptyStr(String str){
if(str == null || "".equals(str)){
return false;
}else if("null".equlas(str)){
return false;
}else{
return true;
}
}
//18:Unicode转中文 -----完全不懂
public static String decodeUnicode(String str){
char achar;
int len = str.length();
StringBuffer outBuffer = new String Buffer(len);
for( int x= 0;x<len;){
achar = str.charAt(x++);
if(achar == '\\'){
achar = str.cahrAt(x++);
if( achar == 'u'){ //Read the xxx
int value = 0;
for(int i = 0; i<4;i++){
achar = str.charAt(x++);
switch(char){
case ‘0’:
case ‘1’:
case ‘2’:
case ‘3’:
case ‘4’:
case ‘5’:
case ‘6’:
case ‘7’:
case ‘8’:
case ‘9’:
value =(value << 4) + achar -'0';
break;
case 'a';
case 'b';
case 'c';
case 'd';
case 'e';
case 'f';
value =(value << 4) + 10 +achar -'a';
break;
case 'A';
case 'B';
case 'C';
case 'D';
case 'E';
case 'F;
value =(value << 4) + 10 +achar -'A';
break;
default:
throw new IllegalArgumentException( "Malformed \\uxxxx encoding.");
}
}
outBuffer.append( (char)value );
}else{
if(achar == 't'){achar = '\t';}
else if(achar == 'r'){achar ='\r';}
else if(achar == 'n'){achar ='\n';}
else if(achar == 'f'){achar ='\f';}
}
outBuffer.append(achar);
}
}else{outBuffer.append(achar);
}
return outBuffer.toString();
}
//19:获取字符串的长度,如果有中文,则每个中文字符记为 2位
public static int length(String value){
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
/*获取字段值得长度,如果包含中文字符,则每个中文字符长度为2,否则为1*/
for( int i = 0 ;i <value.length(); i++){
/*获取每一个字符*/
String temp = value.subString(i,i+1);
if(temp.matched(chinese)){ //判断是否为中文字符
valueLength += 2; //中文字符长度为2
}else{
valueLength += 1; //其他字符长度为1
}
}
return valueLength;
}
//20 :Json相关
/查看json
public static final void select(JSONObject jsonObj,List<Object> properties){
if(jsonObj == null ) return ;
if(properties == null || properties.isEmpty())return ;
//创建一个list集合
List<Object> toRemoveList = new ArrayList<>();
for(Object key : jsonObj.keySet()){
if(!properties.contains(key)){ //properties中不包含Json对象中的键
toRemoveList.add(key);
}
//properties中包含 JSON对象的键
Object val = josnObj.get(key);
if( val instanceof JSONObject ){ select( (JSONObject)val,properties);} //json对象
if( val instanceof JSONArray){
JSONArray array = (JSONArray)val;
if(array.size() == 0){toRemoveList.add(key);}
else{
List<Object> toRemoveList2 = new ArrayList<Object>();
for(int idx = 0;idx < array.size();idx ++){
Object val2 = array.get(idx);
if(val2 instanceof String && StringUtils.isBlank((String)val2)){toRemoveList2.add(val2);}
if(val2 instanceof JSONObject){select( (JSONObject)val2,properties);}
}
for(Object val2 : toRemoveList2){ array.remove(val2);}
}
}
}
for(Object key : toRemoveList){ jsonObj.remove(key);}
}
//数据返回Json格式 0失败 1成功
public static String resultToJson(int flag,Object val,List<Object> properties){
if(flag == 0) {return resultToJson("error",val,properties);}
return resultToJson("success",val,properties);
}
//resultToJson方法的重载
public static String resultToJson(String code,Object val, List<Object> properties){
Map<String,Object> map = new HashMap<String, Object>();
map.put("code",code);
map.put("data",val);
map.put("token",SystemUtils.getSessionId());
//每次接口返回数据就会显示code,data,token
Map<String ,String> returnmap = getReturnMap();
if(null != return Map && !returnMap.isEmpty()){
map.putAll(returnMap);
}
//返回结果为list 时
if(val instanceof List && "sucess".equals(code)){
List list = (List) val;
for(Object o : list){
//所有的model都继承了BaseModel ,如果List装的是Model
if( o instanceof BaseModel){
BaseModel bm = (BaseModel) o ;
map.put("curPage",String.format("%d",bm.getCurPage()));
map.put("totalRecords",String.format("%d",bm.getTotalRecords()));
break; //就是设置列表list--分页数据
}
}
}
//返回一般结果
JSONObject jsonObj = JSONObject.fromObject(map); //map转换为Json对象
Object obj = jsonObj.get("data"); //获得响应数据
if(obj Instanceof JSONObject){ //Json对象
select(jsonObj.getJSONObject("data"),properties);
}
if(obj Instanceof JSONArray){ //Json数组
JSONArray array = (JSONArray )obj;
for( int idx = 0; idx < array.size(); idx++){
Object val2 = array.get(idx); //得到每一个 数组对象
if( val2 instanceof JSONObject){
select( (JSONObject)val2,properties);
}
}
}
//最后
return jsonObj.toString();
}
//21:执行成功 ,数据返回Json格式
public static String resultSuccessToJson(Object val ){
return resultToJson(1 , val , null);
}
public static String resultSuccessToJson(Object val,List<Object> properties){
return resultToJson(1 , val , properties);
}
//22:执行失败,数据返回json格式
public static String resultFailToJson(Object val){
return resultToJson(0 , val , null);
}
public static String resultFailToJson(Exception e){
if(e == null){return resultToJson(0, null, null); }
//自己写的ExceptionWithCode
if(e instanceof ExceptionWithCode){
ExceptionWithCode ec = (ExceptionWithCode)e;
return resultToJson(ec.getCode,ec.getMessage(),null);
}else if(e instanceof BadSqlGrammarException){//sql语法错误
BadSqlGrammarException eb = (BadSqlGrammarException)e;
return resultToJson(0,String.format("SQL错误:%s",eb.getCause().toString()),null);
}else if(e instanceof SQLException){
SQLException es = (SQLException)e;
return resultToJson(0,String.format("SQL错误:%s",es.getCause().toString()),null);
}else if(e instanceof RecoverableDataAccessException){
RecoverableDataAccessExceptiones er = (RecoverableDataAccessException)e;
return resultToJson(0,String.format("SQL错误:%s",er.getCause().toString()),null);
}
e.printStackTrace();//其他异常
return resultToJson(0, e.getMessage(),null);
}
//23:将字符串转换为 ASC|| 码
public static String getCnASCII(String cnStr){
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnstr.getBytes();
for( int i = 0; i <bGBK.length; i++){strBuf.append(Integer.toHexString(bGBK[i] & 0xff) ); }
return strBuf.soString();
}
//24:IP地址相关
/获取Ip地址
public static final String getIpAddress(InetAddress inetAddress) throws Exception{
byte[] ip = inetAddress.getAddress();
//下面代码是把mac地址拼装成String
StringBuilder sb = new StringBuilder();
for( int i = 0; i < ip.length; i++){
//第一个不拼.
if(i != 0 ){sb.append(".");}
String s = String.format("%d",ip[i] < 0 ? ip[i] +256:ip[i]);
sb.append(s);
}
return sb.toString();
}
//24.1 根据Ip地址获取mac地址 ipAddress : 127.0.0.1,不知道有啥用
public static String getLocalMac(String ipAddress) throws SocketException,UnKnownHostException{
String str = "";
String macAddress = "";
final String LOOPBACK_ADDRESS ="127.0.0.1" ;
//如果为127.0.0.1,则获取本地mac地址
if(LOOPBACK_ADDRESS .equals(ipAddress) ){
InetAddress inetAddress = InetAddress.getLocalHost();
NByte[] mac = etworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
//把mac地址拼装成String
StringBuilder sb = new StringBuilder();
for( int i= 0;i< mac.length; i++){
if(i != 0 ){sb.append("-");}
//mac[i] & 0xff 是为了把 byte 转化为正整数
String s = Integer.toHexString(mac[i] & 0xff);
sb.append(s.length() == 1? 0+s :s);
}
//把字符串所有小写字母改为大写 为正规的ma地址并返回
macAddress = sb.toString().trim.toUpperCase();
return macAddress;
}else{
//获取非本地Ip的mac地址
try{
System.out.println(ipAddress);
Process p = Runtime.getRuntime().exec("nbtstat -A"+ipAddress);
System.out.println("===process==="+p);
//输入流 (参数:进程)
InputStreamReader ir = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(ir);
while( (str = br.readLine()) != null ){ //说明 进程读取到数据
if(str.indexof("MAC")>1){
macAddress = str.substring(str.indexof("MAC")+9,str.length());
macAddress = macAddress.trim();
System.out.println("mac地址:"+macAddress);
break;
}
}
p.destroy();
br.close();
}catch(IOException e){}
return macAddress;
}
}
//24.2 输入流转字符串,挺神奇
public static String inputStream2String(InputStream in) throws IOException{
StringBuffer out = new StringBuffer();
byte[] b = new Byte[4096];
for( int n; (n =in.read(b)) != -1;){
out.append(new String(b,0,n));
}
return out.toString();
}
//25 文件相关
//获取文件的绝对路径,根据文件位置url
public static String getAbsFileName(String url) throws Exception{
URL lurl = new URL(url);
return lurl.getPath();
}
//获取绝对路径,根据url
public static String getAbsPath(String url) throws Exception{
File file = new File( getAbsFileName(url));
if( file.getParent() != null ){ return file.getParent().replaceAll("\\\\","/"); }
else {return null;}
}
//获取文件名 (url)
public static String getFileName(String url) throws Exception{
File file = new File( getAbsFileName(url));
return file.getName();
}
//获取文件扩展名(url)
public static String getExtName(String url) throws Exception{
String fileName = getFileName(url);
return fileName.substring(fileName.lastIndexOf("."));
}
//获取文件扩展名(path)
public static String getExtNameByPath(String path) throws Exception{
File file = new File( path);
return file.getName().substring(file.getName().lastIndexOf("."));
}
//26获取properties
public static final Set<Object> getProperties(List<?> list,String property){
Set<Object> retlist = new LinkedHashList<>();
for(Object o : list){
try{
if(null == value || "".equlas(value.toString())) continue;
retlist.add(value);
}catch(Exception e){
e.printStackTrace();
}
}
return retlist;
}
}
好累。全部手抄的。有的还看不懂,方法可能用的很原始。没办法,CV不了。