前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >常用的Java开发自定义工具类UtilsTools

常用的Java开发自定义工具类UtilsTools

作者头像
ZhangXianSheng
发布2019-07-02 17:48:34
发布2019-07-02 17:48:34
2.2K00
代码可运行
举报
运行总次数:0
代码可运行

日常开发中经常会遇到一些常用频繁的数据类型转换、日期格式转换、非空校验、避免重复造轮子写代码一般我们一般会封装一个常用的Utils开放工具类;

最近在开发中遇到数组、list、string的转换比较频繁,公司的原有的工具类没法满足所以对原有的工具类进行修改,为了后面其他项目也能引用将原有工具类进行了优化:

UtilsTools.java

代码语言:javascript
代码运行次数:0
运行
复制
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UtilsTools {

	/**判断传入值是否为空*/
	public static boolean isEmpty(String str) {
		if ( str == null || "".equals(str) || "null".equals(str) || "undefined".equals(str)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**判断传入值是否不为空*/
	public static boolean isNotEmpty(String str) {
		if (!"".equals(str) && str != null) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * String字符串转数字数组
	 * @param ids:传入的数组字符串
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static Integer[] StrToArray(String ids,String Separator){
		try {
			List<Integer> list = new ArrayList<Integer>();
			String[] strs = ids.split(Separator);
			for (String id : strs) {
				if(!UtilsTools.isEmpty(id)){
					Integer id1 =  Integer.parseInt(id);
					if(!list.contains(id1)){
						list.add(id1);
					}
				}
			}
			return list.toArray(new Integer[list.size()]);
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * String字符串转String数组
	 * @param ids:传入的数组字符串
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static String[] StrToArrayString(String ids,String Separator){
		try {
			String[] strs = ids.split(Separator);
			return strs;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * 字符串直接转List<Integer>
	 * @param ids:传入的数组字符串
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static List<Integer> StrToIntegerList(String ids,String Separator){
		try {
			List<Integer> list = new ArrayList<Integer>();
			String[] strs = ids.split(Separator);
			for (String id : strs) {
				if(!UtilsTools.isEmpty(id)){
					Integer id1 =  Integer.parseInt(id);
					if(!list.contains(id1)){
						list.add(id1);
					}
				}
			}
			return list;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * 字符串直接转List<String>
	 * @param ids:传入的数组字符串
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static List<String> StrToStringList(String ids,String Separator){
		try {
			List<String> list = new ArrayList<String>();
			String[] strs = ids.split(Separator);
			for (String str : strs) {
				if(!UtilsTools.isEmpty(str)){
					if(!list.contains(str)){
						list.add(str);
					}
				}
			}
			return list;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * List<String>直转String
	 * List<String>转带自定义分隔符字符串
	 * @param list:传入的List集合,内部参数String
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static String StringListToStr(List<String> list,String Separator){
		String strs="";
		try {
			for (String str : list) {
				strs+=str+Separator;
			}
			//截取最后一位多余的分割符号(取分割符长度,长度大于1的分割符同样有效)
			strs=strs.substring(0, strs.length()-Separator.length());
			return strs;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * List<Integer>直转String
	 * List<Integer>转带自定义分隔符字符串
	 * @param list:传入的List集合,内部参数Integer
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static String IntgerListToStr(List<Integer> list,String Separator){
		String strs="";
		try {
			for (Integer str : list) {
				strs+=str.toString()+Separator;
			}
			//截取最后一位多余的分割符号(取分割符长度,长度大于1的分割符同样有效)
			strs=strs.substring(0, strs.length()-Separator.length());
			return strs;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * String[]直转String
	 * String[]转带自定义分隔符字符串
	 * @param String[]:传入的String[]
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static String IntgerArrayToStr(String[] array,String Separator){
		String strs="";
		try {
			for (String str : array) {
				strs+=str+Separator;
			}
			//截取最后一位多余的分割符号(取分割符长度,长度大于1的分割符同样有效)
			strs=strs.substring(0, strs.length()-Separator.length());
			return strs;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * Integer[]直转String
	 * Integer[]转带自定义分隔符字符串
	 * @param Integer[]:传入的Integer[]
	 * @param Separator:分隔符支持','及'&'等自定义分隔符
	 * */
	public static String IntgerArrayToStr(Integer[] array,String Separator){
		String strs="";
		try {
			for (Integer str : array) {
				strs+=str.toString()+Separator;
			}
			//截取最后一位多余的分割符号(取分割符长度,长度大于1的分割符同样有效)
			strs=strs.substring(0, strs.length()-Separator.length());
			return strs;
		} catch (RuntimeException e) {
			throw e;
		}
	}
	
	/**
	 * ','分割的字符串转Integer数组
	 */
	public static Integer[] getInts(String ids){
		try {
			List<Integer> list = new ArrayList<Integer>();
			String[] strs = ids.split(",");
			for (String id : strs) {
				if(!UtilsTools.isEmpty(id)){
					Integer id1 =  Integer.parseInt(id);
					if(!list.contains(id1)){
						list.add(id1);
					}
				}
			}
			return list.toArray(new Integer[list.size()]);
		} catch (NumberFormatException e) {
			throw e;
		}
	}
	
	//补零
	public static String  fillZero(Integer num){
		if(num<10){
			return "0"+num;
		}
		
		return ""+num;
	}

	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date toDate(String strDate) {
		if(isEmpty(strDate)){
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}
	
	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date toSortDate(String strDate) {
		if(isEmpty(strDate)){
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}

	public static String toDateString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return formatter.format(date);
	}
	
	public static String toLongDateHzString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
		return formatter.format(date);
	}
	
	public static String toShortDateHzString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
		return formatter.format(date);
	}
	
	
	public static String toDateFullString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(date);
	}
	public static String toShortDateString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
		return formatter.format(date);
	}
	public static String toShortDateTimeString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日 HH:mm");
		return formatter.format(date);
	}
	public static String toTimeString(Date date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
		return formatter.format(date);
	}
	
	public static String getEncoding(String str) {      
	       String encode = "GB2312";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s = encode;      
	              return s;      
	           }      
	       } catch (Exception exception) {      
	       }      
	       encode = "ISO-8859-1";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s1 = encode;      
	              return s1;      
	           }      
	       } catch (Exception exception1) {      
	       }      
	       encode = "UTF-8";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s2 = encode;      
	              return s2;      
	           }      
	       } catch (Exception exception2) {      
	       }      
	       encode = "GBK";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s3 = encode;      
	              return s3;      
	           }      
	       } catch (Exception exception3) {      
	       }      
	      return "";      
	   }     
	
	
	/**
	 * 比较两个日期是否相等
	 */
	public static boolean compareDate(Date date1,Date date2){
		
		if((date1 == null && date2 == null) || (date1!=null && date2!=null && date1.compareTo(date2) == 0)){
			return true;
		}else{
			return false;
		}
	}
	
	
	/**
     * 拆分集合
     * @param <T>
     * @param resList  要拆分的集合
     * @param count    每个集合的元素个数
     * @return  返回拆分后的各个集合
     */
    public static  <T> List<List<T>> splitArray(List<T> resList,int count){
        
        if(resList==null ||count<1)
            return  null ;
        List<List<T>> ret=new ArrayList<List<T>>();
        int size=resList.size();
        if(size<=count){ //数据量不足count指定的大小
            ret.add(resList);
        }else{
            int pre=size/count;
            int last=size%count;
            //前面pre个集合,每个大小都是count个元素
            for(int i=0;i<pre;i++){
                List<T> itemList=new ArrayList<T>();
                for(int j=0;j<count;j++){
                    itemList.add(resList.get(i*count+j));
                }
                ret.add(itemList);
            }
            //last的进行处理
            if(last>0){
                List<T> itemList=new ArrayList<T>();
                for(int i=0;i<last;i++){
                    itemList.add(resList.get(pre*count+i));
                }
                ret.add(itemList);
            }
        }
        return ret;
    }
    //匹配正则表达式(只能是字母或数字)
    public static boolean matches(String content){
    	String regex = "^[A-Za-z0-9]+$";
		Pattern pattern = Pattern.compile(regex);
		Matcher match = pattern.matcher(content);
		if(match.matches()){
			return true;
		}else{
			return false;
		}
    }
  //匹配正则表达式
    public static boolean matches(String regex,String content){
		Pattern pattern = Pattern.compile(regex);
		Matcher match = pattern.matcher(content);
		if(match.matches()){
			return true;
		}else{
			return false;
		}
    }

}

支持非空校验、常用日期格式转换、String字符串Array数组List集合互转,支持分割符内容自定义、表达式匹等;

UtilsTools工具类使用(带注释):

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档