java工具类之常用工具类

import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * 常用工具类
 * 
 * @author zql
 */
public class Common {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Common.class);
	
	/**
	 * 打印异常信息
	 * 
	 * @param method 方法名称
	 * @param e 异常对象
	 */
	public static void printException(String method, Exception e) {
		if (method != null) {
			logger.error(method);
		}
		if (e != null) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 比较两个字符串是否相同
	 * 
	 * @param s1 字符串1
	 * @param s2 字符串2
	 * @return 比较结果,相同返回true,不相同返回false
	 */
	public static boolean equalsString(String s1, String s2) {
		if (s1 == null) {
			return (s2 == null);
		} else {
			return s1.equals(s2);
		}
	}
	
	/**
	 * 比较两个字符串是否相同,忽略大小写
	 * 
	 * @param s1 字符串1
	 * @param s2 字符串2
	 * @return 比较结果,相同返回true,不相同返回false
	 */
	public static boolean equalsStringIgnoreCase(String s1, String s2) {
		if (s1 == null) {
			return (s2 == null);
		} else {
			return s1.equalsIgnoreCase(s2);
		}
	}
	
	/**
	 * 比较两个字符
	 * 
	 * @param s1 字符串1
	 * @param s2 字符串2
	 * @return 比较结果,s1 = s2返回值等于0,s1 < s2返回值小于0,s1 > s2返回值大于0
	 */
	public static int compareString(String s1, String s2) {
		if (s1 == null) {
			return (s2 == null) ? 0 : -1;
		} else {
			return s1.compareTo(s2);
		}
	}
	
	/**
	 * 比较两个字符串是否相同,忽略大小写
	 * 
	 * @param s1 字符串1
	 * @param s2 字符串2
	 * @return 比较结果,s1 = s2返回值等于0,s1 < s2返回值小于0,s1 > s2返回值大于0
	 */
	public static int compareStringIgnoreCase(String s1, String s2) {
		if (s1 == null) {
			return (s2 == null) ? 0 : -1;
		} else {
			return s1.compareToIgnoreCase(s2);
		}
	}
	
	/**
	 * 检查字符串中是否包含另一字符串
	 * 
	 * @param str 需要检查的字符串
	 * @param containsStr 包含的字符串
	 * @return 包含返回true,否则返回false
	 */
	public static boolean containsString(String str, String containsStr) {
		if (str == null || containsStr == null) {
			return false;
		}
		return str.contains(containsStr);
	}
	
	/**
	 * 检查字符串中是否包含另一字符串,检查过程中忽略大小写
	 * 
	 * @param str 需要检查的字符串
	 * @param containsStr 包含的字符串
	 * @return 包含返回true,否则返回false
	 */
	public static boolean containsStringIgnoreCase(String str, String containsStr) {
		if (str == null || containsStr == null) {
			return false;
		}
		return str.toLowerCase().contains(containsStr.toLowerCase());
	}
	
	/**
	 * 字符串转换整数
	 * 
	 * @param str 字符串
	 * @param defaultValue 转换成的缺省整数
	 * @return 字符串转换的整数,转换失败,则返回缺省整数
	 */
	public static int stringToInteger(String str, int defaultValue) {
		int iValue;
		try {
			iValue = Integer.parseInt(str);
		} catch (Exception e) {
			iValue = defaultValue;
		}
		return iValue;
	}
	
	/**
	 * 字符串转换长整数
	 * 
	 * @param str 字符串
	 * @param defaultValue 转换成的缺省整数
	 * @return 字符串转换的整数,转换失败,则返回缺省长整数
	 */
	public static long stringToLong(String str, long defaultValue) {
		long lValue;
		try {
			lValue = Long.parseLong(str);
		} catch (Exception e) {
			lValue = defaultValue;
		}
		return lValue;
	}
	
	/**
	 * 字符串转换字节
	 * 
	 * @param str 字符串
	 * @param defaultValue 转换成的缺省字节
	 * @return 字符串转换的字节,转换失败,则返回缺省字节
	 */
	public static byte stringToByte(String str, byte defaultValue) {
		byte value;
		try {
			value = Byte.parseByte(str);
		} catch (Exception e) {
			value = defaultValue;
		}
		return value;
	}
	
	/**
	 * 字符串是否等于null或者Empty
	 * 
	 * @param str 字符串
	 * @return 字符串是否等于null或者Empty
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || str.isEmpty());
	}
	
	/**
	 * 根据指定的字符串将字符串分割为字符串数组
	 * 
	 * @param str 被切分的字符串
	 * @param regex 指定用于切分的字符串
	 * @return 被切分的字符串数组
	 */
	public static String[] splitString(String str, String regex) {
		if(!isNullOrEmpty(str)) {
			String[] strArr = str.split(regex);
			if (strArr != null && strArr.length > 0) {
				return strArr;
			}
		}
		return null;
	}
	
	/**
	 * 根据指定的字符串将字符串分割为整数数组
	 * 
	 * @param str 被切分的字符串
	 * @param regex 指定用于切分的字符串
	 * @return 被切分的字符串数组
	 */
	public static int[] splitInteger(String str, String regex) {
		int[] intArr = null;
		if(!isNullOrEmpty(str)) {
			String[] strArr = str.split(regex);
			if (strArr != null && strArr.length > 0) {
				intArr = new int[strArr.length];
				for (int i = 0; i < strArr.length; i++) {
					intArr[i] = stringToInteger(strArr[i], 0);
				}
			}
		}
		return intArr;
	}
	
	/**
	 * 指定的类型是否是包装类
	 * 
	 * @param cls 指定的类型
	 * @return 类型是否是包装类
	 */	
	@SuppressWarnings("rawtypes")
	public static boolean isWrapClass(Class cls) {
		boolean result;
		if (cls == java.sql.Blob.class) {
			return true;
		}
		try {
			Field field = cls.getField("TYPE");
			Class type = (Class)field.get(null);
			result = type.isPrimitive();
		} catch (Exception e) {
			return false;
		}
		return result ? result : cls.equals(String.class);
	}
	
	/**
	 * 指定的类型是否是包装类或者基本类型
	 * 
	 * @param cls 指定的类型
	 * @return 类型是否是包装类或者基本类型
	 */
	@SuppressWarnings("unchecked")
	public static <T> boolean isWarpClassOrSimpleType(Class<T> cls) {
		// object instanceof String, Number, Boolean, Character, null
		boolean result;
		try {
        	// 判断是否为基本类型:int, double, float, long, short, boolean, byte, char,void
        	result = cls.isPrimitive();
        	if (!result) {
        		Field field = cls.getField("TYPE");
        		Class<T> type = (Class<T>)field.get(null);
        		result = type.isPrimitive();
        	}
        } catch (Exception e) {
        	result = false;
        }
		return result ? result : cls.equals(String.class);
	}
	
	/**
	 * 用于对象数组的创建的泛型方法
	 * 
	 * @param ts 可变泛型参数
	 * @return 返回泛型数组
	 */
	@SafeVarargs
	public static <T> T[] arrayOf(T...ts){
		return ts;
	}
	
	/**
	 * 比较两个对象是否相等
	 * 
	 * @param obj1 第一个对象
	 * @param obj2 第二个对象
	 * @return 两个对象相等返回true,否则返回false
	 */
	public static boolean equalsObject(Object obj1, Object obj2) {
		if (obj1 == null) {
			return (obj2 == null);
		}
		return obj1.equals(obj2);
	}
	
	/**
	 * 转换对象为Long对象
	 * 
	 * @param obj 转换的对象
	 * @return 转换后的Long对象,但obj为空或者转换异常时返回-1
	 */
	public static long getLong(Object obj) {
		if (obj == null) {
			return -1;
		}
		try {
			return (Long)obj;
		} catch (Exception e) {
			return -1;
		}
	}
	
	/**
	 * 转换对象为Long对象
	 * 
	 * @param obj 转换的对象
	 * @param min 转换目标值的最小值
	 * @return 转换后的Long对象,如果转换后的Long小于最小值,则返回最小值
	 */	
	public static long getLongMin(Object obj, long min) {
		long result = getLong(obj);
		if (result != -1 && result <= min) {
			result = min;
		}
		return result;
	}
	
	/**
	 * 将一组整形数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(Integer[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 将一组整形数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(int[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 将一组长整形数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 长整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(Long[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
		
	/**
	 * 将一组长整形数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 长整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(long[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 将一组双精度数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 长整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(Double[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 将一组双精度数字组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 长整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(double[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 将一组字符串数组合成一个以指定分隔符分割成的字符串
	 * 
	 * @param items 长整形数字集合
	 * @param separator 分隔符
	 * @return 组合成的字符串
	 */
	public final static String combineString(String[] items, String separator) {
		if (items == null || items.length <= 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			sb.append(items[i]);
			if (i != items.length - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 获取目录名称,如果目录以“/”或者“\”结尾,去除掉结尾字符
	 * 
	 * @param path 原始目录
	 * @return 目标目录结尾不带“/”或者“\”
	 */
	public static String getDirectory(String path) {
		if (isNullOrEmpty(path)) {
			return null;
		}
		if (path.endsWith("\\") || path.endsWith("/")) {
			return path.substring(0, path.length() - 1);
		} else {
			return path;
		}
	}
	
	/**
	 * 创建文件,如果文件所在路径不存在则创建路径
	 * 
     * @param filePath 文件完整名称(包含路径)
     * @return 创建的文件
     */
	public static File createFile(String filePath) {
        File targetFile = new File(filePath);
        if (targetFile.isDirectory()) {
        	targetFile.mkdirs();
        } else {
        	File parentFile = targetFile.getParentFile();
            if (!parentFile.exists()) {
            	parentFile.mkdirs();
            	targetFile = new File(targetFile.getAbsolutePath());
            }
        }
        return targetFile;
    }
	
	/**
	 * 创建文件,如果文件所在路径不存在则创建路径
	 * 
     * @param filePath 文件完整名称(包含路径)
     * @param isDirectory 文件是否为文件夹
     * @return 创建的文件
     */
	public static File createFile(String filePath, boolean isDirectory) {
        File targetFile = new File(filePath);
        if (isDirectory) {
        	targetFile.mkdirs();
        } else {
        	File parentFile = targetFile.getParentFile();
            if (!parentFile.exists()) {
            	parentFile.mkdirs();
            	targetFile = new File(targetFile.getAbsolutePath());
            }
        }
        return targetFile;
    }
	
	/**
	 * 获取用户当前的工作目录
	 * 
	 * @return 用户当前的工作目录
	 */
	public static String getSystemRunPath() {
		return System.getProperty("user.dir");
	}
	
	/**
	 * 对某个数保留小数位数的
	 * 
	 * @param num 某个数
	 * @param type 类型,1四舍五入,2五舍六入,3进位处理(就是直接加1),4直接去掉尾数
	 * @param count 要保留的小数位数
	 * @return 返回double类型的结果<br />
	 * 如果num不是数字时,返回0<br />
	 * 如果不处于类型内,则默认四舍五入<br />
	 * 如果count小于1时,默认为保留两位小数
	 */
	public static double getBigDecimal(String num, int type, int count) {
		if (!isNumber(num)) {
			return 0;
		}
		if (type < 1 || type > 4) {
			type = 1;
		}
		if (count < 1) {
			count = 2;
		}
		double d = Double.parseDouble(num);
		BigDecimal b = new BigDecimal(num);
		switch (type) {
		case 1:
			d = b.setScale(count, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入
			break;
		case 2:
			d = b.setScale(count, BigDecimal.ROUND_HALF_DOWN).doubleValue();//五舍六入
			break;
		case 3:
			d = b.setScale(count, BigDecimal.ROUND_UP).doubleValue();//进位处理(就是直接加1)
			break;
		case 4:
			d = b.setScale(count, BigDecimal.ROUND_DOWN).doubleValue();//直接去掉尾数
			break;
		default:
		}
		return d;
	}
	
	/**
	 * 是否和正则表达式匹配
	 * 
	 * @param regex 正则表达式
	 * @param matchStr 要匹配的字符串
	 * @return 匹配成功返回true,否则返回false;
	 */
	public static boolean isMatch(String regex, String matchStr) {
		if (matchStr == null || matchStr.trim().equals("")) {  
            return false;  
        }
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(matchStr).matches();
	}
	
	/**
	 * 判断字符串是否是正整数
	 * 
	 * @param str
	 * @return 是正整数返回true,否则返回false
	 */
	public static boolean isPositiveInteger(String str) {
		return isMatch("^\\+{0,1}[1-9]\\d*", str);
	}
	
	/**
	 * 判断字符串是否是负整数
	 * 
	 * @param str
	 * @return 是负整数返回true,否则返回false
	 */
	public static boolean isNegativeInteger(String str) {
		return isMatch("^-[1-9]\\d*", str);
	}
	
	/**
	 * 判断字符串是否是整数
	 * 
	 * @param str
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		return isMatch("[-\\+]{0,1}0|^\\+{0,1}[1-9]\\d*|^-[1-9]\\d*", str) ;
	}
	
	/**
	 * 判断字符串是否是正小数
	 * 
	 * @param str
	 * @return 是正小数返回true,否则返回false
	 */
	public static boolean isPositiveDecimal(String str) {
		// 例,因为0.0=0,它的本质是0,小数点后都是0理论上是一个错误的小数,但double类型可支持,如需要则去掉if
		if (isMatch("^[0]\\.[0]+", str)) {
			return false;
		}
		return isMatch("\\+{0,1}\\d{1}\\.\\d+|\\+{0,1}[1-9]{1}\\d*\\.\\d+", str);
	}

	/**
	 * 判断字符串是否是负小数
	 * 
	 * @param str
	 * @return 是负小数返回true,否则返回false
	 */
	public static boolean isNegativeDecimal(String str) {
		// 例,因为0.0=0,它的本质是0,小数点后都是0理论上是一个错误的小数,但double类型可支持,如需要则去掉if
		if (isMatch("^[0]\\.[0]+", str)) {
			return false;
		}
		return isMatch("^-\\d{1}\\.\\d+|^-[1-9]{1}\\d*\\.\\d+", str);
	}
	
	/**
	 * 判断字符串是否是小数
	 * 
	 * @param str
	 * @return 是小数返回true,否则返回false
	 */
	public static boolean isDecimal(String str) {
		// 例,因为0.0=0,它的本质是0,小数点后都是0理论上是一个错误的小数,但double类型可支持,如需要则去掉if
		if (isMatch("^[0]\\.[0]+", str)) {
			return false;
		}
		return isMatch("[-\\+]{0,1}\\d{1}\\.\\d+|[-\\+]{0,1}[1-9]{1}\\d*\\.\\d+", str);
	}
	
	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 * @return 是数字返回true,否则返回false
	 */
	public static boolean isNumber(String str) {
		return isInteger(str) || isDecimal(str);
	}
	
	/**
	 * 获取文件后缀名
	 * 
	 * @param str 文件全名或者文件路径,文件路径请包括文件全名
	 * @return 返回后缀名,不包括点
	 */
	public static String getFileSuffix(String str) {
		return str.substring(str.lastIndexOf(".") + 1);
	}
}


发布了55 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/mr_zql/article/details/96041268