java宝典之字符串String工具类

4 篇文章 0 订阅
package com.ouyeel.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;



/**
 * 字符串常用方法工具类
 * 
 */
public final class StrUtil {

	/**
	 * 此类不需要实例化
	 */
	private StrUtil() {
	}

	/**
	 * 判断一个字符串是否为空,null也会返回true
	 * 
	 * @param str
	 *            需要判断的字符串
	 * @return 是否为空,null也会返回true
	 */
	public static boolean isBlank(String str) {
		return null == str || "".equals(str.trim());
	}

	/**
	 * 判断一个字符串是否不为空
	 * 
	 * @param str
	 *            需要判断的字符串
	 * @return 是否为空
	 */
	public static boolean isNotBlank(String str) {
		return !isBlank(str);
	}

	/**
	 * 判断一组字符串是否有空值
	 * 
	 * @param strs
	 *            需要判断的一组字符串
	 * @return 判断结果,只要其中一个字符串为null或者为空,就返回true
	 */
	public static boolean hasBlank(String... strs) {
		if (null == strs || 0 == strs.length) {
			return true;
		} else {
			// 这种代码如果用java8就会很优雅了
			for (String str : strs) {
				if (isBlank(str)) {
					return true;
				}
			}
		}
		return false;
	}

	public static String reverse(String str, int length) {
		StringBuffer sb = new StringBuffer(str);
		int a = sb.length();
		if (a < length) {
			for (int i = 0; i < length - a; i++) {
				sb.append("0");
			}
		}

		sb = sb.reverse();

		return sb.toString();
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
	}

	/*
	 * string准备被填充的字符串; padded_length填充之后的字符串长度,也就是该函数返回的字符串长度,
	 * 如果这个数量比原字符串的长度要短,lpad函数将会把字符串截取成从左到右的n个字符;
	 * pad_string填充字符串,是个可选参数,这个字符串是要粘贴到string的左边,
	 * 如果这个参数未写,lpad函数将会在string的左边粘贴空格
	 */
	public static String lpad(String str, int padded_length, String pad_string) {
		if (str.length() >= padded_length) {
			return str;
		} else {
			String padStr = BeanUtil.isNull(pad_string) ? " " : pad_string;
			for (int i = 0; i < padded_length - str.length(); i++) {
				str = padStr + str;
			}
		}

		return str;
	}

/*	public static String getTimestampStr() {
		Date currentDate = new Date();

		return DateUtil.DateToString(currentDate, DateStyle.YYYYMMDDHHMMSSSSSS);
	}

	public static String getTimestampStr(DateStyle dateStyle) {
		Date currentDate = new Date();

		return DateUtil.DateToString(currentDate, dateStyle);
	}*/

	/**
	 * 判断一个字符串是否为空,null会返回"",不为null是返回原值
	 * 
	 * @param str
	 *            需要判断的字符串
	 * @return 是否为空,null返回 "",不为null是返回原值
	 */
	public static String isNullStr(String str) {
		if (str != null) {
			return str;
		} else {
			return "";
		}
	}

	/**
	 * 需要进行sha1加密的 sign 字符串组装
	 * 
	 * @param 组装对象
	 * @return 需要进行sha1加密的 sign 字符串
	 */
	public static String getAllComponentsName(Object f) {
		if (f == null) {
			return "";
		}
		String returnStr = "";
		Field[] fields = f.getClass().getDeclaredFields();
		for (Field field : fields) {
			String varName = field.getName();
			try {
				// 获取原来的访问控制权限
				boolean accessFlag = field.isAccessible();
				// 修改访问控制权限
				field.setAccessible(true);
				// 获取在对象f中属性fields[i]对应的对象中的变量
				Object o = field.get(f);
				if (o != null) {
					returnStr = returnStr.trim() + varName + "=" + o + "&";
				}
				// 恢复访问控制权限
				field.setAccessible(accessFlag);
			} catch (IllegalArgumentException ex) {
				ex.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}

		returnStr = returnStr.trim()
				.substring(0, returnStr.trim().length() - 1);
		return returnStr;
	}

	/**
	 * 需要进行sha1加密的 sign 字符串组装
	 * 
	 * @param 组装对象
	 * @return 需要进行sha1加密的 sign 字符串
	 */
	public static String getAllComponentsNameStr(TreeMap<String, String> treeMap) {
		String returnStr = "";
		for (Map.Entry<String, String> entry : treeMap.entrySet()) {
			returnStr = returnStr + "&" + entry.getKey() + "="
					+ entry.getValue();
		}
		returnStr = returnStr.trim().substring(1, returnStr.length());
		return returnStr;
	}

	/**
	 * MapridNull
	 * 
	 * @param
	 * @return
	 */
	public static Map MapridNull(HashMap<String, String> map) {
		Map<String, String> cmap = new HashMap<String, String>();
		cmap.putAll((Map)map.clone());
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (entry.getValue() == null || entry.getValue().equals("")
					|| entry.getValue().equals("null")) {
				cmap.remove(entry.getKey());
			}
		}
		return cmap;
	}

	/**
	 * 需要进行sha1加密的 sign 字符串组装 去空值
	 * 
	 * @param 组装对象
	 * @return 需要进行sha1加密的 sign 字符串
	 */
	public static String Tree2STR(TreeMap<String,String> treeMap) {
		if (treeMap == null) {
			return null;
		}
		if (isNull(treeMap.toString())) {
			return null;
		}
		StringBuffer orgin = new StringBuffer();

		for (Map.Entry<String, String> entry : treeMap.entrySet()) {
			orgin.append("&");
			orgin.append(entry.getKey());
			orgin.append("=");
			Object value=entry.getValue();
			orgin.append(value);
		}
		return orgin.replace(0, 1, "").toString();
	}

	/**
	 * 去除目标对象的null数据,返回一个绝对空的字符串
	 * 
	 * @param valueMap
	 * @param keyName
	 * @return
	 */
	public static String getString(Map valueMap, String keyName) {
		if (valueMap == null) {
			return "";
		} else {
			return valueMap.get(keyName) == null ? "" : valueMap.get(keyName)
					.toString();
		}

	}

	/**
	 * 去除目标对象的null数据,返回一个绝对空的字符串
	 * 
	 * @param target
	 * @return String
	 */
	public static String dnvString(Object target) {
		String str = String.valueOf(target).trim();
		return isNull(str) ? "" : str.replace("{}", "");
	}

	public static boolean isNull(String str) {
		if (null == str)
			return true;
		return "".equals(str) || "null".equals(str);
	}

	public static boolean isNotNull(Object str) {
		return (null != str) && (!"".equals(str.toString().trim()));
	}

	// 把target空的属性,从source复制过来
	public static Object copyNullProperties(Object source, Object target) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo
					.getPropertyDescriptors();

			for (PropertyDescriptor property : propertyDescriptors) {
				Method getter = property.getReadMethod();
				Object targetValue = getter.invoke(target);

				if (targetValue == null
						|| (String.valueOf(targetValue)).trim().equals("")
						|| (String.valueOf(targetValue)).trim().equals("null")) {
					Method setter = property.getWriteMethod();
					Object sourceValue = getter.invoke(source);
					setter.invoke(target, sourceValue);
				}
			}

		} catch (Exception e) {
			System.out.println("transMap2Bean Error " + e);
		}
		return target;
	}
	
	public static String splitString(String str, String temp) {
        String result = null;
        if (str.indexOf(temp) != -1) {
            if (str.substring(str.indexOf(temp)).indexOf("&") != -1) {
                result = str.substring(str.indexOf(temp)).substring(str.substring(str.indexOf(temp)).indexOf("=") + 1,
                        str.substring(str.indexOf(temp)).indexOf("&"));

            } else {
                result = str.substring(str.indexOf(temp)).substring(str.substring(str.indexOf(temp)).indexOf("=") + 1);

            }
        }
        return result;
    }
	/*public static void main(String[] args) {
	}*/
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值