开发中日常操作转化工具类

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public  class Util
{
    /**
     * ERRORTYPE
     */
    public static final String ERRORTYPE = "TYPE";
    
    /**
     * ERRORTYPE_ERROR
     */
    public static final String ERRORTYPE_ERROR = "ERROR";
    
    /**
     * ERRORCODE
     */
    public static final String ERRORCODE = "ERRORCODE";
    
    /**
     * ERRORINFO
     */
    public static final String ERRORINFO = "ERRORINFO";
    
    /**
     * GOPAGE
     */
    public static final String GOPAGE = "GOPAGE";
    
    /**
     * 有效小数
     */
    public static final int EFFECTIVE = 2;
    
    protected static final Log LOG = LogFactory.getLog(Util.class);
    
    /**
     * 移除重复
     * 
     * @param arr
     *            要处理的字符串数
     * @return 处理后的字符串数
     */
    public static String[] removeRepeat(String[] arr)
    {
        if (arr == null)
        {
            return new String[0];
        }
        else
        {
            
            Map<String, String> map = new HashMap<String, String>();
            for (String str : arr)
            {
                String strt = map.get(str);
                if (strt == null)
                {
                    map.put(str, str);
                }
            }
            
            List<String> list = new ArrayList<String>();
            for (Map.Entry<String, String> entry : map.entrySet())
            {
                list.add(entry.getKey());
            }
            
            String[] strArr = new String[list.size()];
            
            return list.toArray(strArr);
        }
    }
    
    /**
     * 移除重复
     * 
     */
    public static String removeRepeat(String str)
    {
        if (str == null)
        {
            return "";
        }
        else
        {
            str = str.replaceAll("^,+", "");
            str = str.replaceAll(",+$", "");
            str = str.replaceAll(",+", ",");
            StringBuffer buf = new StringBuffer();
            for (String strt : removeRepeat(str.split(",")))
            {
                buf.append(strt).append(',');
            }
            
            str = removeEnd(buf.toString());
            return str;
        }
    }
    
    /**
     * 移除开头的逗号
     * 
     */
    public static String removeBegin(String str)
    {
        if (str == null)
        {
            return "";
        }
        else
        {
            Matcher matcher = Pattern.compile("^,+").matcher(str);
            str = matcher.replaceAll("");
            return str;
        }
    }
    
    /**
     * 移除结尾的逗号
     * 
     */
    public static String removeEnd(String str)
    {
        if (str == null)
        {
            return "";
        }
        else
        {
            Matcher matcher = Pattern.compile(",+$").matcher(str);
            str = matcher.replaceAll("");
            return str;
        }
    }
    
    /**
     * 格式化日期
     * @param date 日期
     * @param pattern 格式
     * @return String String
     */
    public static String formatDate(Date date, String pattern)
    {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        
        return format.format(date);
    }
    
    /**
     * 〈计算两个日期相差的天数〉
     * 〈功能详细描述〉
     * @param begin 开始日期
     * @param end 结束日期
     * @return long
     */
    public static long calDays(Date begin, Date end)
    {
        long time = end.getTime() - begin.getTime();
        long days = time / 24 / 60 / 60 / 1000;
        return days;
    }
    
    /**
     * 获取未来第几天的时间yyyy-MM-dd
     * @param dayNum
     * @return
     */
    public static String getNextDay(int dayNum){
    	Calendar cal = Calendar.getInstance(); 
    	Date date = new Date(); 
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
    	String returnDate  ="";
    	try 
    	{ 
	    	cal.setTime(date); 
	    	cal.add(Calendar.DATE, dayNum); 
	    	returnDate = sdf.format(cal.getTime());
    	} 
    	catch (Exception e) 
    	{ 
    		e.printStackTrace(); 
    	}
    return returnDate;
    }
    
    /**
     * 格式化日期
     * @param str 日期字符串
     * @param pattern 格式
     * @return Date Date
     */
    public static Date formatDate(String str, String pattern)
    {
        Date date = null;
        
        try
        {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            
            date = format.parse(str);
        }
        catch (ParseException e)
        {
            date = new Date();
        }
        
        return date;
    }
    
    /**
     * 解析字符
     * 
     * @param key
     *            key
     * @param str
     *            str
     * @return value
     */
    public static String getValue(String key, String str)
    {
        if (key == null || str == null)
        {
            return "";
        }
        String[] strArr = str.split(",");
        
        for (String tempStr : strArr)
        {
            if (key.equals(tempStr.split(":")[0]))
            {
                return tempStr.split(":")[1];
            }
        }
        
        return "";
    }
    
    /**
     * 解析字符
     * 
     * @param key
     *            key
     * @param str
     *            str
     * @return value
     */
    public static int getIntValue(String key, String str)
    {
        int result = 0;
        if (str == null)
        {
            return result;
        }
        String[] strArr = str.split(",");
        
        String value = "0";
        for (String tempStr : strArr)
        {
            if (key.equals(tempStr.split(":")[0]))
            {
                value = tempStr.split(":")[1];
            }
        }
        try
        {
            result = Integer.parseInt(value);
        }
        catch (Exception e)
        {
            result = 0;
        }
        
        return result;
    }
    
    /**
     * 解析字符
     */
    public static String[] getValue(String str)
    {
        if (str == null)
        {
            return new String[0];
        }
        return str.split(",");
    }
    
    /**
     * 直接向用户返回指定信息
     * 
     * @param response
     *            response
     * @param msg
     *            void
     */
    public static void returnMsg(HttpServletResponse response, String msg)
    {
        Writer out = null;
        try
        {
            out = response.getWriter();
            out.write(msg);
            out.close();
        }
        catch (IOException e)
        {
            LOG.error(e);
        }
    }
    
    /**
     * 
     * @param str str
     * @param reg reg
     * @param newValue newValue
     * @return String
     */
    public static String replace(String str, String reg, String newValue)
    {
        if (!isEmpty(str))
        {
            Matcher matcher = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(str);
            
            str = matcher.replaceAll(newValue);
        }
        return str;
    }
    
    /**
     * 
     * @param str str
     * @param reg reg
     * @param newValue newValue
     * @param param param
     * @return String
     */
    public static String replace(String str, String reg, String newValue, int param)
    {
        if (!isEmpty(str))
        {
            Matcher matcher = Pattern.compile(reg, param).matcher(str);
            
            str = matcher.replaceAll(newValue);
        }
        return str;
    }
    
    /**
     * 〈移除字符串中的js代码
     * 
     * @param str
     *            str
     * @return String
     */
    public static String removeScript(String str)
    {
        if (str == null || "".equals(str))
        {
            return "";
        }
        
        int param = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL;
        Matcher matcher = Pattern.compile("<script>.*</script>", param).matcher(str);
        str = matcher.replaceAll("");
        return str;
    }
    
    /**
     * 字符串转成整数
     * 
     * @param str
     *            字符
     * @return 数字
     */
    public static int parseInt(String str)
    {
        int result = 0;
        try
        {
            result = Integer.parseInt(str);
        }
        catch (Exception e)
        {
            result = 0;
        }
        return result;
    }
    
    /**
     * 〈文件重命名〉
     * 
     * @param realPath
     *            文件绝对路径
     * @param newName
     *            新文件名
     * @return String
     */
    public static String rename(String realPath, String newName)
    {
        File file = new File(realPath);
        
        //包含后缀的文件名
        String fileName = file.getName();
        
        //不包含后的文件名
        String name = fileName.substring(0, fileName.lastIndexOf('.'));
        
        //带后的新文件名称
        newName = fileName.replace(name, newName);
        
        realPath = realPath.replace(fileName, newName);
        
        if (file.exists())
        {
            try
            {
                if (!file.renameTo(new File(realPath)))
                {
                   throw new Exception();
                }
                
            }
            catch (Exception e)
            {
               e.printStackTrace();
            }
        }
        
        return newName;
    }
    
    /**
     * 把数组转换成字符串,并以逗号分隔
     * 
     * @param arr
     *            arr
     * @return 转换结果
     */
    public static String arrayToString(String[] arr)
    {
        
        if (arr == null)
        {
            return "";
        }
        StringBuffer buf = new StringBuffer();
        for (String str : arr)
        {
            if (str != null && !"".equals(str))
            {
                buf.append(str).append(',');
            }
        }
        String result = buf.toString();
        result = result.replaceAll(",$", "");
        return result;
    }
    
    /**
     * 写Excel
     * 
     * @param response
     *            response
     * @param file
     *            file
     */
    public static void writeExcel(HttpServletResponse response, File file)
    {
        if (file != null && file.exists())
        {
       
        
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        InputStream inStream = null;
        try
        {
            inStream = new FileInputStream(file);
            int len = inStream.read();
            while (len != -1)
            {
                response.getWriter().write(len);
                len = inStream.read();
            }
        }
        catch (Exception e)
        {
            
          e.printStackTrace();
        }
        finally
        {
            Util.close(inStream);
        }
        }
    }
    
    
    
    
    /**
     * 
     * @param reg
     *            reg
     * @param str
     *            str
     * @return boolean
     */
    public static boolean test(String reg, String str)
    {
        Matcher matcher = Pattern.compile(reg).matcher(str);
        return matcher.find();
    }
    
    
    /**
     *关闭流
     * @param ins void
     */
    public static void close(InputStream ins)
    {
        if (ins != null)
        {
            try
            {
                ins.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 关闭流
     * @param ous void
     */
    public static void close(OutputStream ous)
    {
        if (ous != null)
        {
            try
            {
                ous.close();
            }
            catch (IOException e)
            {
               e.printStackTrace();
            }
        }
    }
    
    /**
     * 
     * 〈重新组装查询条件〉
     * 〈如果查询条件包含"_"就在"_"之前加上转义字符"/"〉
     * @param queryCondition 查询条件
     * @return String
     */
    public static String resetCondition(String queryCondition)
    {
        char[] temps = queryCondition.toCharArray();
        
        //查询条件
        StringBuffer condition = new StringBuffer();
        
        //重新组装查询条件的字符串,如果包"_"就在"_"之前加上转义字符"/"
        for (char temp : temps)
        {
            if ('_' == temp)
            {
                condition.append('/').append(temp);
            }
            else
            {
                condition.append(temp);
            }
        }
        
        return condition.toString();
    }
    
    /**
     *〈验证字符串是否为空〉
     * @param str str
     * @return boolean
     */
    public static boolean isEmpty(String str)
    {
        return str == null || "".equals(str);
    }
    
    /**
     *〈验证字符串是否不为空〉
     * @param str str
     * @return boolean
     */
    public static boolean notEmpty(String str)
    {
        return !isEmpty(str);
    }
    
    /**
     *〈验证字符串是否为空〉
     * @param str str
     * @return boolean
     */
    public static boolean isEmpty(Object str)
    {
        return str == null;
    }
    
    /**
     *〈〈验证字符串是否为空〉
     * @param list list
     * @return boolean
     */
    public static boolean isEmpty(List<?> list)
    {
        return list == null || list.isEmpty();
    }
    
    /**
     *〈〈验证字符串是否不为空〉
     * @param list list
     * @return boolean
     */
    public static boolean notEmpty(List<?> list)
    {
        return !isEmpty(list);
    }
    
    /**
     *〈验证字符串是否为空〉
     * @param map 待处理的集合
     * @return boolean
     */
    public static boolean isEmpty(Map<?, ?> map)
    {
        return map == null || map.isEmpty();
    }
    
    /**
     *〈验证字符串是否不为空〉
     * @param map 待处理的集合
     * @return boolean
     */
    public static boolean notEmpty(Map<?, ?> map)
    {
        return !isEmpty(map);
    }
    
    /**
     *〈转换为小写
     * @param str str
     * @return String
     */
    public static String lowerCase(String str)
    {
        
        if (str != null)
        {
            str = str.toLowerCase(Locale.CHINESE);
        }
        
        return str;
    }
    
    /**
     *〈转换为大写〉
     * @param str str
     * @return String
     */
    public static String upperCase(String str)
    {
        
        if (str != null)
        {
            str = str.toUpperCase(Locale.CHINESE);
        }
        
        return str;
    }
    
    /**
     *〈一句话功能描述〉
     * @param cls cls
     * @param methodName methodName
     * @param classArr classArr
     * @return Method 
     */
    @SuppressWarnings("unchecked")
    public static Method getMethod(Class<?> cls, String methodName, Class[] classArr)
    {
        Method mtd = null;
        try
        {
            mtd = cls.getDeclaredMethod(methodName, classArr);
        }
        catch (SecurityException e)
        {
            LOG.error(e);
        }
        catch (NoSuchMethodException e)
        {
            LOG.error(e);
        }
        
        return mtd;
    }
    
    /**
     * 获取当前服务器ip
     * @return String
     */
    public static String getLocalSiteIP()
    {
        String siteString = "";
        try
        {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface = null;
            InetAddress ipAddress = null;
            while (netInterfaces.hasMoreElements())
            {
                networkInterface = (NetworkInterface)netInterfaces.nextElement();
                ipAddress = (InetAddress)networkInterface.getInetAddresses().nextElement();
                if (ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress()
                        && ipAddress.getHostAddress().indexOf(":") == -1)
                {
                    siteString = ipAddress.getHostAddress();
                }
            }
        }
        catch (Exception e)
        {
            e.toString();
        }
        return siteString;
    }
    
    /**
     * 〈trim公共方法
     * 〈功能详细描述
     * @param str str
     * @return String
     */
    public static String trim(String str)
    {
        if (str != null)
        {
            str = str.trim();
        }
        
        return str;
    }
    
    /**
     * 检查算法表达式合法性
     * @param calculateScript 计算脚本
     * @return 返回true表达式合?,false表达式不合法
     */
    public static boolean checkCalculateScript(String calculateScript)
    {
        return true;
    }
    
    /**
     * 获取系统时间
     * @return 当前系统时间
     */
    public static Date getSysDate()
    {
        SimpleDateFormat ft = null;
        Calendar cal = Calendar.getInstance();
        
        // 格式可以自己根据要求修改
        ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = ft.format(cal.getTime());
        Date nowDate = null;
        try
        {
            nowDate = ft.parse(dateTime);
        }
        catch (ParseException e)
        {
            LOG.error(e);
            //            e.printStackTrace();
        }
        
        return nowDate;
    }
    
    /**
     * 〈根据系统当前时间获取下一个月日期对象〉
     * 〈功能详细描述〉
     * @return Date
     */
    public static Date getNextMonth()
    {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        return cal.getTime();
    }
    
    
    /**
     * 设置文件输出流的文件名
     * @param failName 文件名
     * @param response void
     */
    public static void responseSetHeader(String failName, HttpServletResponse response)
    {
        response.setHeader("Content-disposition", "attachment; filename=" + failName);
        response.setContentType("application/msexcel");
    }

    /**
     *〈为空验证〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean empty(String str, String prop)
    {
        if (str == null)
        {
            return false;
        }
        
        if ("".equals(str.trim()))
        {
            return false;
        }
        
        return true;
    }
    
    /*
     *〈按字节验证字符串长度〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    /*    public static boolean byteLength(String str, String prop)
        {
            int length = 20;
            
            if (Util.isEmpty(str))
            {
                return true;
            }
            
            char[] chars = str.toCharArray();
            int len = 0;
            for (int i = 0; i < chars.length; i++)
            {
                len++;
                
                //判断是否非字母
                if (chars[i] / 0x80 == 0)
                {
                    len++;
                }
            }
            
            return len <= length;
        }*/

    /**
     *〈非法字符〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean lawless(String str)
    {
        boolean result = false;
        
        if (Util.isEmpty(str))
        {
            result = true;
        }
        
        result = !Util.test("^[-~!@#$%^&*()_+|=\\;':\",./<>?]+$", str);
        
        return result;
    }
    
    /**
     *〈验证只能为汉字〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean chinese(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^[\u4E00-\u9FA5]+$", str);
    }
    
    /**
     *〈验证只能为字母〉
     * @param str 待验证字符串
     * @return boolean
     */
    protected static boolean letter(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^[a-zA-Z]+$", str);
    }
    
    /**
     *〈验证数字是否在指定范围〉
     * @param str str
     * @param prop prop
     * @return boolean
     */
    protected static boolean number(String str)
    {
        
        return true;
    }
    
    /**
     *〈验证手机号码〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean mobile(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^1\\d{10}$", str);
    }
    
    /**
     *〈验证IP〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean checkIP(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        String pattern = "^(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\.(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])){3}$";
        return Util.test(pattern, str);
    }
    
    /**
     *〈验证日期〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean date(String str)
    {
        String pattern = "";
        
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try
        {
            format.parse(str);
        }
        catch (ParseException e)
        {
            return false;
        }
        
        return true;
    }
    
    /**
     *〈验证邮编〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean postalCode(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        //暂未实现
        
        return true;
    }
    
    /**
     *〈验证EMAIL〉
     * @param str 待验证字符串 
     * @param prop prop
     * @return boolean
     */
    protected static boolean email(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^[a-zA-Z0-9_.]+@\\w+\\-?\\w+(\\.\\w+)$", str);
    }
    
    /*
     *〈验证身份证〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    /*    public static boolean checkID(String str)
        {
            if (Util.isEmpty(str))
            {
                return true;
            }
            
            if (Util.test("^\\d{17}[xX\\d]$", str))
            {
                return checkID18(str);
            }
            else if (Util.test("^\\d{15}$", str))
            {
                return checkID15(str);
            }
            else
            {
                return false;
            }
        }*/

    /*private static boolean checkID18(String str)
    {
        String year = str.substring(6, 2);
        String month = str.substring(8, 2);
        String day = str.substring(10, 2);
        if (!Util.test("^\\d\\d$", year))
        {
            return false;
        }
        if (!isMonth(month))
        {
            return false;
        }
        if (!isDay(day))
        {
            return false;
        }
        if (Util.parseInt(month) == 2 && Util.parseInt(day) > FEB_DAYES)
        {
            return false;
        }
        return true;
    }
    
    private static boolean checkID15(String str)
    {
        String year = str.substring(ID15_YEAR, 4);
        String month = str.substring(ID15_MONTH, 2);
        String day = str.substring(ID15_DAY, 2);
        
        if (!isYear(year))
        {
            return false;
        }
        
        if (!isMonth(month))
        {
            return false;
        }
        
        if (!isDay(day))
        {
            return false;
        }
        
        if (Util.parseInt(month) == 2 && Util.parseInt(day) > FEB_DAYES)
        {
            return false;
        }
        
        return true;
    }*/

    /**
     *〈验证必须为数字〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean mustNum(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^\\d+$", str);
    }
    
    /**
     *〈体重验证〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean avoirdupois(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^([3-9]\\d|1\\d\\d)(\\.\\d{0,2})?$", str);
    }
    
    /**
     *〈验证身高〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean stature(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^([89]\\d|[12]\\d\\d)(\\.\\d{0,2})?$", str);
    }
    
    /**
     *〈验证年龄〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean age(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^([1-9]|[1-9]\\d?)$", str);
    }
    
    /**
     *〈验证鞋码〉
     * @param str 待验证字符串
     * @param prop prop
     * @return boolean
     */
    protected static boolean shoeSize(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("(^[34]\\d$)|(^50$)", str);
    }
 
	/**
	 * 判断是否为数字,包含浮点型
	 * @param str
	 * @return
	 */
    public static boolean checkNum(String str)
    {
        if (Util.isEmpty(str))
        {
            return true;
        }
        
        return Util.test("^\\d+(\\.\\d+){0,1}$", str);
    }
    
    public static void main(String[] args) {
		System.out.println(checkNum("12"));
	}
    
}

 

你可能感兴趣的:(工具类)