Java 工具类

查看代码
/**
 * CLASS    : DstCommonCheck
 * VERSION  : 0.01.0001
 * DATE     : 2001/04/25
 * AUTHOR   : NCT zht
 * HISTORY  : 2001/04/25
 **/

package com.xxx.tool;

import com.csvreader.CsvReader;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <P><B>TRECK系统 - 服务部品共通部分 DstCommonCheck 文件</B></P>
 **/
public class DstCommonFunction {
    public DstCommonFunction() {
    }

    /**
     * 检查是否为浮点类型
     * @return boolean
     */
    public boolean isDouble(String verDouble) {
        try {
            System.out.println("[CommonCheck]:isDouble START");
            double verRtn = Double.parseDouble(verDouble);
            System.out.println("[CommonCheck]:isDouble END");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查是否为整数类型
     * @return boolean
     */
    public boolean isLong(String verLong) {
        try {
            System.out.println("[CommonCheck]:isLong START");
            long verRtn = Long.parseLong(verLong);
            System.out.println("[CommonCheck]:isLong END");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查是否为单精度类型
     * @return boolean
     */
    public boolean isFloat(String verFloat) {
        try {
            System.out.println("[CommonCheck]:isFloat START");
            float verRtn = Float.parseFloat(verFloat);
            System.out.println("[CommonCheck]:isFloat END");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 加单引号
     * @return String
     */
    public String addQuota(String verStr) {
        try {
            //System.out.println("[CommonCheck]:addQuota START");
            int pos = 0;
            String str = verStr;
            pos = str.indexOf("'");
            while (pos >= 0) {
                str = str.substring(0, pos + 1) + "'" + str.substring(pos + 1);
                pos = str.indexOf("'", pos + 2);
            }
            //System.out.println("[CommonCheck]:addQuota END");
            return str;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 去单引号
     * @return String
     */
    public String dropQuota(String verStr) {
        try {
            System.out.println("[CommonCheck]:dropQuota START");
            int pos = 0;
            String str = verStr;
            pos = str.indexOf("''");
            while (pos >= 0) {
                str = str.substring(0, pos + 1) + str.substring(pos + 2);
                pos = str.indexOf("''", pos + 1);
            }
            System.out.println("[CommonCheck]:dropQuota END");
            return str;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 校验字符串长度
     * @return boolean
     */
    public int checkLength(String verStr) {
        try {
            System.out.println("[CommonCheck]:checkLength START");
            String verstr = verStr.trim();
            if (verstr.equals("")) {
                return 0;
            }
            byte byteArry[] = verstr.getBytes();
            System.out.println("[CommonCheck]:checkLength END");
            return byteArry.length;
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 获得错误画面的路径
     * @return String
     */
    public String getErrMsgPath() {
        System.out.println("[CommonCheck]:getErrMsgPath START");
        System.out.println("[CommonCheck]:getErrMsgPath END");
        return "onload=\"popupSubWindow('/cn/toyota_sales/CmnMsg0000.jsp')\"";
    }

    /**
     * 获得错误画面的路径script
     * @return String
     */
    public String getErrMsgScript() {
        System.out.println("[CommonCheck]:getErrMsgScript START");
        System.out.println("[CommonCheck]:getErrMsgScript END");
        return "onload=\"args = new Array(); args[0] = window.name; window.showModalDialog('/cn/toyota_sales/CmnMsg0000.jsp',args);\"";
    }

    /**
     * 判断是否字符串为代码类型,字符串重的字符范围全在在0-9,A-Z或a-z之间
     * @param strIn 待判断的字符串
     * @return true为代码 false 不为代码								<BR>
     * @author zhangliqiang
     * @version 20040331
     */
    public static boolean isCode(String strIn) {
        for (int i = 0; i < strIn.length(); i++) {
            if (!((strIn.charAt(i) >= '0' && strIn.charAt(i) <= '9')
                    || (strIn.charAt(i) >= 'a' && strIn.charAt(i) <= 'z')
                    || (strIn.charAt(i) >= 'A' && strIn.charAt(i) <= 'Z'))) {
                return false;
            }
        }
        return true;
    }

    /**
     *  判断是否是数值型数据
     * @param strIn String
     * @return boolean
     */
    public static boolean isNum(String strIn) {
        for (int i = 0; i < strIn.length(); i++) {
            if (!((strIn.charAt(i) >= '0' && strIn.charAt(i) <= '9'))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 对字符串NULL进行处理
     * @param strNull 待处理的字符串
     * @return 字符串								<BR>
     * @author shanlihua
     * @version 20040410
     */
    public static String isNull(String strNull) {
        String strTemp = "";
        if (strNull == null) {
            return "";
        } else {
            strTemp = strNull.trim();
            return strTemp;
        }
    }



    /**********************************************************<BR>
     * 函数名:		IsEnglishCharacter  			            <BR>
     * 机能概要:		判断是否全为半角字符   						<BR>
     *                                             	        <BR>
     * 参数:	strin								    	    <BR>
     * 返回值:	True	全为半角									<BR>
     *			False	不全为半角								<BR>
     *********************************************************/

    public static boolean IsHalfWidth(String strin)
    {

        try{
            //    byte[] b = strin.getBytes("X-SJIS");
            byte[] b = strin.getBytes();
            if (b.length > strin.length () ) {
                return false;
            }
        }catch(Exception e){}

        return true;
    }

    /**
     * 将Year与Month拼成yyyy/mm形式
     * @param strYear 年
     * @param strMonth 月
     * @return yyyy/mm								<BR>
     * @author liujia
     * @version 20040411
     */
    public static String concatYearMonth(String strYear, String strMonth) {
        String strYearMonth = "";
        String strVirgule = "/";
        strYearMonth = (strYear.concat(strVirgule)).concat(strMonth);
        return strYearMonth;

    }
    /**
     * 格式化日期
     * @param date yyyymmdd
     * @return yyyy/mm/dd
     * 财务、车辆改善, 2007/08/28,Added by huoxuanwei
     */
    public String formatDate(String date){
        if(date == null || date.length()!= 8 ) {
            return date;
        }
        return date.substring(0,4)+ "/" + date.substring(4,6)
                + "/" + date.substring(6,8);
    }

    /**
     * 将金额转化为形式999,999,999.99
     * @param dAccount 待转化的金额
     * @return strAccount	转化后的字符串							<BR>
     * @author liangxiao
     * @version 20040409
     */
    public String getAccount(double dAccount) {
        String strAccout = "";
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);
        strAccout = formatter.format(dAccount);
        return strAccout;
    }

    /**
     * 格式化数字
     * @param num
     * @return 9999999.99
     * 财务、车辆改善, 2007/08/28,Added by huoxuanwei
     */
    public String formatNumber(String num){
        if(num == null || num.length() == 0 ) {
            return "0.00";
        }
        DecimalFormat formater = new DecimalFormat("0.00");
        return formater.format(Double.parseDouble(num));
    }

    /**
     * 将数值转化为形式999,999,999
     * @param strNumber 待转化的数值
     * @return strAccount 转化后的字符串							<BR>
     * @author liujia
     * @version 20040419
     */
    public String getNumber(String strNumber) {
        String strAccout = "";
        int iNumber = Integer.parseInt(strNumber);
        NumberFormat formatter = NumberFormat.getNumberInstance();
        strAccout = formatter.format(iNumber);
        return strAccout;
    }

    /**
     * 对NULL转换为零字符串处理
     * @param strNull 待处理的字符串
     * @return 字符串<BR>
     * @author shanlihua
     * @version 20040413
     */
    public String isNullToZero(String strNull) {
        String strTemp = "";
        if (strNull == null) {
            return "0";
        } else {
            strTemp = strNull.trim();
            if (strTemp.equals("")) {
                return "0";
            }
            return strTemp;
        }
    }

    /**
     *  将当前时间转换为YYYYMMDDHHMMSS格式
     * @return String
     *  wangjingyue     add   2004-04-13
     */
    public static String getCurrenttime2MMDDHHMMSS() {
        String strTemp = null;
        /**
         java.util.Calendar cal = java.util.Calendar.getInstance();
         StringBuffer strRetVal = new StringBuffer(64);
         strRetVal.append(cal.get(cal.YEAR));
         String[] lStrAppMMDDHHMMSS = new String[5];
         String[] lStrAppPara = new String[5];
         lStrAppPara[0] = ( (cal.get(cal.MONTH) + 1) + "").trim();
         lStrAppPara[1] = (cal.get(cal.DAY_OF_MONTH) + "").trim();
         lStrAppPara[2] = ( (cal.get(cal.HOUR_OF_DAY)) + "").trim();
         lStrAppPara[3] = ( (cal.get(cal.MINUTE)) + "").trim();
         lStrAppPara[4] = (cal.get(cal.SECOND) + "").trim();
         for (int i = 0; i < lStrAppPara.length; i++) {
         if (lStrAppPara[i].length() == 1) {
         lStrAppMMDDHHMMSS[i] = "0" + lStrAppPara[i];
         strRetVal.append(lStrAppMMDDHHMMSS[i]);
         }
         else {
         lStrAppMMDDHHMMSS[i] = lStrAppPara[i];
         strRetVal.append(lStrAppMMDDHHMMSS[i]);
         }
         }*/
        // begin wangjingyue  modify   2004-04-15
        //精确到毫秒级别,避免重复
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date sysDate = new Date();
        strTemp = formatter.format(sysDate);
        //end
        return strTemp;
    }

    /**
     * 年月转换(如:"200304"——>"Apr-03")
     * @param strYYYYMM 待转化的年月(YYYYMM)
     * @return strAccount 转化后的字符串<BR>
     * @author shanlihua
     * @version 20040414
     */
    public String getMonth(String strYYYYMM) {
        int iMonth = Integer.parseInt(strYYYYMM.substring(4));
        String strYear = strYYYYMM.substring(0, 4);
        String strMonth = "";
        String strResult = "";

        switch (iMonth) {
            case 1:
                strMonth = "Jan";
                break;
            case 2:
                strMonth = "Feb";
                break;
            case 3:
                strMonth = "Mar";
                break;
            case 4:
                strMonth = "Apr";
                break;
            case 5:
                strMonth = "May";
                break;
            case 6:
                strMonth = "Jun";
                break;
            case 7:
                strMonth = "Jul";
                break;
            case 8:
                strMonth = "Aug";
                break;
            case 9:
                strMonth = "Sep";
                break;
            case 10:
                strMonth = "Oct";
                break;
            case 11:
                strMonth = "Nov";
                break;
            case 12:
                strMonth = "Dec";

        }

        strResult = strMonth + "-" + strYear.substring(2);
        return strResult;

    }

    /**
     * 检查日期格式,格式为YYYY/MM返回TRUE
     * @param strDate 待检查的的年月(YYYY/MM)
     * @return boolean
     * @author Caizhiguo
     * @version 20040416
     */
    public static boolean checkDateFormat(String strDate) {
        //检查变量是否为NULL
        if (strDate == null) {
            return false;
        }
        //检查日期长度
        if (strDate.length() != 7) {
            return false;
        }
        //检查分隔符
        if (!strDate.substring(4, 5).equals("/")) {
            return false;
        }
        //检查年
        try {
            int year = Integer.parseInt(strDate.substring(0, 4));
            if (!(year > 0 && year <= 9999)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        //检查月
        try {
            int month = Integer.parseInt(strDate.substring(5, 7));
            if (!(month > 0 && month < 13)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 检查日期格式为YYYY/MM的日期1是否在日期2以前(可以等于)
     * @param strDate1 待检查的的年月1(YYYY/MM)
     * @param strDate2 待检查的的年月2(YYYY/MM)
     * @return boolean true:日期1在日期2以前或者为同一天,false:日期1在日期2以后
     * @author Caizhiguo
     * @version 20040520
     */
    public boolean checkDate1BeforeDate2(String strDate1, String strDate2) {
        //检查日期格式是否正确
        if (!checkDateFormat(strDate1)) {
            return false;
        }
        if (!checkDateFormat(strDate2)) {
            return false;
        }

        //需要比较的年1
        int iYear1 = 0;
        //需要比较的月1
        int iMonth1 = 0;
        //需要比较的年2
        int iYear2 = 0;
        //需要比较的月2
        int iMonth2 = 0;
        try {
            //获取年月
            iYear1 = Integer.parseInt(strDate1.substring(0, 4));
            iMonth1 = Integer.parseInt(strDate1.substring(5, 7));
            iYear2 = Integer.parseInt(strDate2.substring(0, 4));
            iMonth2 = Integer.parseInt(strDate2.substring(5, 7));
        } catch (Exception e) {
            return false;
        }

        //System.out.println(":" + iYear1);
        //System.out.println(":" + iMonth1);
        //System.out.println(":" + iYear2);
        //System.out.println(":" + iMonth2);

        //比较年份,如果年份1大于年份2,返回false
        if (iYear1 > iYear2) {
            return false;
            //如果年份相同,比较月份
        } else if (iYear1 == iYear2) {
            //比较月份,如果月份1大于月份2,返回false
            if (iMonth1 > iMonth2) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查日期格式为YYYY/MM的日期是否在现在年月以前(包括当前月)
     * @param strDate 待检查的的年月(YYYY/MM)
     * @return boolean
     * @author Caizhiguo
     * @version 20040416 updated at 20040520
     */
    public boolean checkDateBeforeNow(String strDate) {
        //检查日期格式是否正确
        if (!checkDateFormat(strDate)) {
            return false;
        }
        //获得当前的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
        Date dt = new Date();
        String strNow = sdf.format(dt);

        //检查日期是否满足要求
        return checkDate1BeforeDate2(strDate, strNow);

    }

    /**
     * 对空串转换为NULL串处理
     * @param strIn 待处理的字符串
     * @return 字符串<BR>
     * @author dongzekun
     * @version 20040418
     */
    public String changeToNull(String strIn) {
        String strTemp = "";
        if (strIn == null) {
            return strIn;
        } else {
            strTemp = strIn.trim();
            if (strTemp.equals("")) {
                return null;
            }
            return strTemp;
        }
    }

    /**
     * 格式化字符串,前面补零
     * @param strArg 要格式化的字符串
     * @param iLen 格式化成几位
     * @return String 格式化后的结果
     * @author liujia
     * @version 20040420
     */
    public String fomatMumber(String strArg, int iLen) {
        while (strArg.length() < iLen) {
            strArg = "0" + strArg;
        }
        return strArg;
    }

    /**
     * 检查目标年份是否合法,合法返回TRUE
     * @param strTargetYear 待检查的的年
     * @return boolean
     * @author zhangyongming,updated by Caizhiguo
     * @version 20040421
     */
    public static boolean checkYearFormat(String strTargetYear) {
        //为null,返回false
        if (strTargetYear == null) {
            return false;
        }
        //长度不为4返回false
        if (strTargetYear.length() != 4) {
            return false;
        }
        //检查年
        try {
            int year = Integer.parseInt(strTargetYear);
            if (!(year > 0 && year <= 9999)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 为调用服务器端shell文件(shell文件功能是从PART.txt文件把数据插入到SRV_parts_M )
     * @param command 命令
     * @return 运行结果
     * @throws java.lang.InterruptedException
     * @throws IOException
     */
    public int runCommand(String command) throws InterruptedException,
            IOException {
        int returnValue = 0;
        //  log.trace(3, "CmnFileDirectoryModel", "runCommand", "strat");
        System.out.println(
                ".......................command=[" + command + "].......");
        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec(command);
            p.waitFor();
            returnValue = p.exitValue();
            System.out.println(
                    "............<<<<<<<<<<<<<<.......returnValue=["
                            + returnValue
                            + "].......");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (IllegalThreadStateException e) {
            e.printStackTrace();
            throw e;
        }
        return returnValue;

    }

    /**
     * 计算d的前i天
     * @param d 输入的日期
     * @param i 天数
     * @return 输出的日期
     */
    public Date dayBeforeIt(Date d, int i) {
        Date dateTemp = new Date();
        dateTemp.setTime(d.getTime() - i * 3600 * 24 * 1000);
        return dateTemp;
    }

    /**
     * 判断字符串是否为扩展的代码类型,只包含如下字符:
     * A-Z,a-z,0-9,_(下划线),-(短横线)
     * @param strCode 待检查的字符串
     * @return true 格式满足 false 格式不满足
     * @author Caizhiguo
     * @version 1.0
     */
    public static boolean isExtendCode(String strCode) {
        Pattern p = Pattern.compile("[^A-Za-z0-9_-]+");
        Matcher m = p.matcher(strCode);
        boolean bRst = m.find();
        if (bRst) {
            return false;
        }
        return true;
    }

    /**
     * 判断字符串是否为扩展的可以包含空格的代码类型,只包含如下字符:
     * A-Z,a-z,0-9,_(下划线),-(短横线) (半角空格)
     * @param strCode 待检查的字符串
     * @return true 格式满足 false 格式不满足
     * @author Caizhiguo
     * @version 1.0
     */
    public static boolean isExtendWithSpaceCode(String strCode) {
        Pattern p = Pattern.compile("[^A-Za-z0-9_ -]+");
        Matcher m = p.matcher(strCode);
        boolean bRst = m.find();
        if (bRst) {
            return false;
        }
        return true;
    }

    /**
     * 将时间加iNum月
     * @param strDate YYYYMM
     * @param iNum 所加的月数并且所加减月数在12个月内
     * @return 年月
     * @author liangxiao
     * @version 1.0
     */
    public String getAddMonth(String strDate, int iNum) {
        String strYear = strDate.substring(0, 4);
        String strMonth = strDate.substring(4);

        int iMonth = Integer.parseInt(strMonth) + iNum;
        int iYear = Integer.parseInt(strYear);
        if (iMonth > 12) {
            //跨年处理(加年)
            iMonth = iMonth - 12;
            iYear = iYear + 1;
        } else if (iMonth <= 0) {
            //跨年处理(减年)
            iMonth = iMonth + 12;
            iYear = iYear - 1;
        }
        strMonth = String.valueOf(iMonth);
        strYear = String.valueOf(iYear);
        //格式化输出
        strYear = "0000" + strYear;
        strMonth = "00" + strMonth;
        strYear = strYear.substring(strYear.length() - 4);
        strMonth = strMonth.substring(strMonth.length() - 2);
        return strYear + strMonth;
    }

    /**
     * 根据传入的月份取得对应的数据库表中的列名
     * @param iMonth 传入的月份
     * @return 对应的表的列名
     * @author liangxiao
     * @version 1.0
     */
    public String getMonthColsName(int iMonth) {
        String strColName = "";
        switch (iMonth) {
            case 1:
                strColName = "UPDJANPREDICT";
                break;
            case 2:
                strColName = "UPDFEBPREDICT";
                break;
            case 3:
                strColName = "UPDMARPREDICT";
                break;
            case 4:
                strColName = "UPDAPRPREDICT";
                break;
            case 5:
                strColName = "UPDMAYPREDICT";
                break;
            case 6:
                strColName = "UPDJUNPREDICT";
                break;
            case 7:
                strColName = "UPDJULPREDICT";
                break;
            case 8:
                strColName = "UPDAUGPREDICT";
                break;
            case 9:
                strColName = "UPDSEPPREDICT";
                break;
            case 10:
                strColName = "UPDOCTPREDICT";
                break;
            case 11:
                strColName = "UPDNOVPREDICT";
                break;
            case 12:
                strColName = "UPDDECPREDICT";
        }
        return strColName;
    }

    /**
     * 格式转换
     * @param inNum 待转换数据
     * @param n 取小数点后几位
     * @return 转换结果
     **/
    public static String format(double inNum, int n) {

        double dPow;
        double dReturnValue = 0;
        String StrTmp;

        StrTmp = "##########0";
        //传入n值为小数点后位数
        if (n > 0) {
            StrTmp += ".";
        }
        for (int i = 0; i < n; i++) {
            StrTmp += "0";
        }

        DecimalFormat form = new DecimalFormat(StrTmp);

        dPow = Math.pow(10, n);

        dReturnValue = inNum * dPow;

        dReturnValue = Math.round(dReturnValue);

        dReturnValue /= dPow;

        return form.format(dReturnValue);

    }
    /**
     * 检查两个时间差别是否在idayNO天内,日期格式为yyyy/MM/dd
     * @param strDateFrom 待检查开始日期
     * @param strDateTo   待检查结束日期
     * @param iDayNO       待检查之间的天数
     * @return true 日期满足要求 false 日期不满足要求
     * @throws ParseException
     */
    public static boolean checkRangeOfDate(String strDateFrom,String strDateTo,
                                    int iDayNO) {
        Date dateFrom;
        Date dateTo;
        try {
            SimpleDateFormat fordate = new SimpleDateFormat("yyyy/MM/dd");
            dateFrom = fordate.parse(strDateFrom);
            dateTo=fordate.parse(strDateTo);
            GregorianCalendar gcFrom = new GregorianCalendar();
            GregorianCalendar gcTo = new GregorianCalendar();
            gcFrom.setTime(dateFrom);
            gcTo.setTime(dateTo);
            int days =(int) ((gcTo.getTimeInMillis() - gcFrom.getTimeInMillis())
                    / (1000 * 60 * 60 * 24));
            //起始日期大于结束日期
            if (days < 0) {
                return false;
            } else if (days > iDayNO) {
                return false;
            } else {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查strDateTo日期是否在strDateFrom之后,日期格式为yyyy/MM/dd
     * @param strDateFrom 待检查开始日期
     * @param strDateTo   待检查结束日期
     * @return true 满足要求; false 不满足要求
     */
    public boolean checkDateAfter(String strDateFrom,String strDateTo){
        SimpleDateFormat fordate = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Date dateFrom = fordate.parse(strDateFrom);
            Date dateTo = fordate.parse(strDateTo);
            int iTemp = dateTo.compareTo(dateFrom);
            if (iTemp >= 0) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断是否为空
     * @param strIn DO取消日
     * @return true 为空 false 不为空
     */
    public boolean IsEmpty(String strIn){
        if ( (strIn != null) && (strIn != "")&&(strIn.length() > 0)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 检查strDateTo和strDateFrom是否成对出现
     * @param strDateFrom 开始日期
     * @param strDateTo   结束日期
     * @return true 满足要求; false 不满足要求
     */
    public boolean checkDateEmpty(String strDateFrom,String strDateTo){
        //都不为空
        if((strDateFrom != null && !strDateFrom.equals("")) &&
                (strDateTo != null && !strDateTo.equals(""))){
            return true;
        }
        //都为空
        if((strDateFrom == null || strDateFrom.equals("")) &&
                (strDateTo == null || strDateTo.equals(""))){
            return true;
        }
        return false;
    }


    /*****************************************************<BR>
     * 函数名:	IsNull									<BR>
     * 机能概要:	空字符串的判断						    <BR>
     *                                                     <BR>
     * 参数:		strin	待检查的字符串			        <BR>
     * 返回值:		True:	空								<BR>
     *				False:	非空								<BR>
     *********************************************************/
    public static boolean IsNull(String strin){

        if(strin == null) return true;
        if(DeleteSpace(strin).equals ("")) return true;
        return false;
    }


    /*****************************************************<BR>
     * 函数名:	DeleteSpace                           <BR>
     * 机能概要:  删除字符串开头和末尾的空格				  <BR>
     *                                                   <BR>
     * 参数:		strin:要删除的字符串			          <BR>
     * 返回值:		处理后的字符串					      <BR>
     *********************************************************/
    public static String DeleteSpace(String strin){

        boolean bFlag = true;
        String strReturnValue = "";
        strin = strin.trim();

        while(bFlag){
            if(strin.length() <= 0){
                break;
            }
            String strStart = strin.substring(0,1);
            String strEnd = strin.substring(strin.length() - 1);
            if(strEnd.equalsIgnoreCase(" ")){
                strin = strin.substring(0,strin.length() - 1);
            }
            else if(strStart.equalsIgnoreCase(" ")){
                strin = strin.substring(1,strin.length());
            }
            else{
                bFlag = false;
            }
        }
        strReturnValue = strin;
        return strReturnValue;
    }



    /*****************************************************<BR>
     * 函数名:	  GetCurrentDate                        <BR>
     * 机能概要:	  获取当前的日期		                    <BR>
     *                                                     <BR>
     * 参数:		nFormat返回的格式				            <BR>
     *				0:"YYYYMMDD"		7:"DD/MM/YYYY"		<BR>
     *				1:"YYYY/MM/DD"		8:"DD-MM-YYYY"		<BR>
     *				2:"YYYY-MM-DD"		9:"DDMMYY"		    <BR>
     *				3:"YYMMDD"			10:"DD/MM/YY"		<BR>
     *				4:"YY/MM/DD"		11:"DD-MM-YY"		<BR>
     *				5:"YY-MM-DD"		12:"YYYY年MM月DD日" <BR>
     *				6:"DDMMYYYY"		13:"YY年MM月DD日" <BR>
     * 返回值:		指定格式的当前日期                     <BR>
     *********************************************************/
    public static String GetCurrentDate(int nFormat){

        String strReturnValue = "";
        String strYear, strMonth, strDate;

        GregorianCalendar GreDate = new GregorianCalendar();
        strYear  = new Integer(GreDate.get(GreDate.YEAR)).toString ();
        strMonth = new Integer(GreDate.get(GreDate.MONTH) + 1).toString ();
        strDate  = new Integer(GreDate.get(GreDate.DATE)).toString ();

        strReturnValue = GetFormatedDate(strYear,strMonth,strDate,nFormat);
        return strReturnValue;
    }




    /*****************************************************<BR>
     * 函数名称:		GetCurrentTime                      <BR>
     * 机能概要:	获取当前的时间						    <BR>
     *                                                     <BR>
     * 参数:		nFormat返回的时间格式			          <BR>
     *				0:"HHMMSS"								<BR>
     *				1:"HH/MM/SS"							<BR>
     *				2:"HH-MM-SS"							<BR>
     * 返回值:指定格式的当前时间								<BR>
     *********************************************************/
    public static String GetCurrentTime(int nFormat){

        String strReturnValue = "";
        GregorianCalendar GreDate = new GregorianCalendar();

        switch(nFormat){
            case 0:
                strReturnValue = SupplyLength(new Integer(GreDate.get(GreDate.HOUR_OF_DAY)).toString (),2) +
                        SupplyLength(new Integer(GreDate.get(GreDate.MINUTE)).toString (),2) +
                        SupplyLength(new Integer(GreDate.get(GreDate.SECOND)).toString (),2);
                break;
            case 1:
                strReturnValue = SupplyLength(new Integer(GreDate.get(GreDate.HOUR_OF_DAY)).toString (),2) + "/" +
                        SupplyLength(new Integer(GreDate.get(GreDate.MINUTE)).toString (),2) + "/" +
                        SupplyLength(new Integer(GreDate.get(GreDate.SECOND)).toString (),2);
                break;
            case 2:
                strReturnValue = SupplyLength(new Integer(GreDate.get(GreDate.HOUR_OF_DAY)).toString (),2) + "-" +
                        SupplyLength(new Integer(GreDate.get(GreDate.MINUTE)).toString (),2) + "-" +
                        SupplyLength(new Integer(GreDate.get(GreDate.SECOND)).toString (),2);
                break;
        }

        return strReturnValue;
    }


    /*****************************************************<BR>
     * 函数名:		GetFormatedDate                     <BR>
     * 机能概要:		按照指定的格式转换日期					<BR>
     *                                                     <BR>
     * 参数:			strYear有效的年份			            <BR>
     *					strMonth有效的月份					<BR>
     *					strDate有效的日				        <BR>
     *					nFormat指定的返回格式		            <BR>
     *				0:"YYYYMMDD"	7:"DD/MM/YYYY"			<BR>
     *				1:"YYYY/MM/DD"	8:"DD-MM-YYYY"			<BR>
     *				2:"YYYY-MM-DD"	9:"DDMMYY"			    <BR>
     *				3:"YYMMDD"		10:"DD/MM/YY"			<BR>
     *				4:"YY/MM/DD"	11:"DD-MM-YY"			<BR>
     *				5:"YY-MM-DD"	12:"YYYY年MM月DD日"		<BR>
     *				6:"DDMMYYYY"	13:"YY年MM月DD日"		<BR>
     * 返回值:		指定格式的日期		                    <BR>
     *********************************************************/
    public static String GetFormatedDate(String strYear, String strMonth,
                                         String strDate, int nFormat)
    {

        String strReturnValue = "";

        switch(nFormat){
            case 0:
                strReturnValue = SupplyLength(strYear,4) +
                        SupplyLength(strMonth,2) +
                        SupplyLength(strDate,2);
                break;
            case 1:
                strReturnValue = SupplyLength(strYear,4) + "/" +
                        SupplyLength(strMonth,2) + "/" +
                        SupplyLength(strDate,2);
                break;
            case 2:
                strReturnValue = SupplyLength(strYear,4) + "-" +
                        SupplyLength(strMonth,2) + "-" +
                        SupplyLength(strDate,2);
                break;
            case 3:
                strReturnValue = SupplyLength(strYear,4).substring (2) +
                        SupplyLength(strMonth,2) +
                        SupplyLength(strDate,2);
                break;
            case 4:
                strReturnValue = SupplyLength(strYear,4).substring (2) + "/" +
                        SupplyLength(strMonth,2) + "/" +
                        SupplyLength(strDate,2);
                break;
            case 5:
                strReturnValue = SupplyLength(strYear,4).substring (2) + "-" +
                        SupplyLength(strMonth,2) + "-" +
                        SupplyLength(strDate,2);
                break;
            case 6:
                strReturnValue = SupplyLength(strDate,2) +
                        SupplyLength(strMonth,2) +
                        SupplyLength(strYear,4);
                break;
            case 7:
                strReturnValue = SupplyLength(strDate,2) + "/" +
                        SupplyLength(strMonth,2) + "/" +
                        SupplyLength(strYear,4);
                break;
            case 8:
                strReturnValue = SupplyLength(strDate,2) + "-" +
                        SupplyLength(strMonth,2) + "-" +
                        SupplyLength(strYear,4);
                break;
            case 9:
                strReturnValue = SupplyLength(strDate,2) +
                        SupplyLength(strMonth,2) +
                        SupplyLength(strYear,4).substring (2);
                break;
            case 10:
                strReturnValue = SupplyLength(strDate,2) + "/" +
                        SupplyLength(strMonth,2) + "/" +
                        SupplyLength(strYear,4).substring (2);
                break;
            case 11:
                strReturnValue = SupplyLength(strDate,2) + "-" +
                        SupplyLength(strMonth,2) + "-" +
                        SupplyLength(strYear,4).substring (2);
                break;
            case 12:
                strReturnValue = SupplyLength(strYear, 4) + "年" +
                        SupplyLength(strMonth, 2) + "月" +
                        SupplyLength(strDate, 2) + "日";
                break;
            case 13:
                strReturnValue = SupplyLength(strYear, 4).substring(2) + "年" +
                        SupplyLength(strMonth, 2) + "月" +
                        SupplyLength(strDate, 2) + "日";
                break;
        }

        return strReturnValue;
    }


    /*****************************************************<BR>
     * 函数名:	SupplyLength				            <BR>
     * 机能概要:	将输入的字符串前加0变成指定长的字符串			<BR>
     *                                                     <BR>
     * 参数:		strin	待转换的字符串					<BR>
     *				nLength 指定的长度		                <BR>
     * 返回值:		处理后的字符串				            <BR>
     *********************************************************/
    public static String SupplyLength(String strin,int nLength)
    {

        String strReturnValue="";
        int nNum;

        nNum = nLength - strin.length ();
        strReturnValue = strin;

        for (int i = 1; i <= nNum; i++){
            strReturnValue = "0" + strReturnValue;
        }

        return strReturnValue;
    }


    /**
     * 检查strDate是否是日期,格式为YYYY/MM/DD
     * @param strDate  检查日期
     * @return true 满足要求; false 不满足要求
     */
    public static boolean checkDateTen(String strDate){
        if (CheckDate(strDate)) {
            if (strDate.length() == 0 || strDate.length() == 10) {
                return true;
            }
        }
        return false;
    }



    /*****************************************************<BR>
     * 函数名称:CheckDate                             <BR>
     * 机能概要:  日期类型CHECK					        <BR>
     *     	分割符="/"                                         <BR>
     * 参数:	Strig inStr		待CHECK的字符串            <BR>
     *
     * 返回值:     true :	输入的日期正确                <BR>
     *				    false :	输入的日期错误                <BR>
     *********************************************************/
    public static boolean CheckDate(String inStr ){
        String inPos = "/" ;
        return CheckDate(inStr,inPos);
    }



    /*****************************************************<BR>
     * 函数名称:CheckDate                             <BR>
     * 机能概要:  日期类型CHECK					        <BR>
     *                                                 <BR>
     * 参数:	Strig inStr		待CHECK的字符串            <BR>
     *				String inPos	分割符              <BR>
     *
     * 返回值:     true :	输入的日期正确                <BR>
     *				    false :	输入的日期错误                <BR>
     *********************************************************/
    public static boolean CheckDate(String inStr, String inPos){
        String numStr = "1234567890";
        String checkedStr = null ;
        //长度及空检查
        if (inStr.trim().length () == 0) {
            return true;
        }
        if (inStr.trim().length () > 10 || inStr.trim().length () < 8) {
            return false;
        }
        int flg = 0;
        for (int i = 0;i<inStr.trim().length() ;i++ ) {
            if(inPos.indexOf(inStr.charAt(i),0) == 0){
                flg ++;
            } else if (numStr.indexOf(inStr.charAt(i),0)==-1) {
                return false;
            }
        }
        if (flg != 2) {
            return false;
        }
        int start = inStr.indexOf(inPos,0);
        int end   = inStr.indexOf(inPos,start + 1);
        if (start == 0 || end == inStr.trim().length() - 1 ) {
            return false;
        }
        checkedStr = CheckDate(inStr.substring(0,start),
                inStr.substring(start+1,end),
                inStr.substring(end+1,inStr.trim().length()));
        if (!checkedStr.equals("111")) {
            return false;
        }

        return true;
    }



    /*****************************************************<BR>
     * 函数名称:CheckDate                             <BR>
     * 机能概要:  日期类型CHECK					        <BR>
     *                                                 <BR>
     * 参数:		strYear		CHECK的年份	            <BR>
     *				strMonth	CHECK的月份              <BR>
     *				strDate		CHECK的日期              <BR>
     * 返回值:     "111":	输入的日期正确                <BR>
     *				 ^^^								      <BR>
     *				 |||________________年:1:正确  0:错误  <BR>
     *				 ||_________________月:1:正确  0:错误  <BR>
     *				 |__________________日:1:正确  0:错误  	  <BR>
     *********************************************************/
    public static String CheckDate(String strYear, String strMonth,
                                   String strDate)
    {
        int intReturnOk = 0;
        int intReturnYearError  = 1;
        int intReturnMonthError = 2;
        int intReturnDateError  = 3;
        int intReturnDayError   = 4;
        int intYear				= 0;
        int intMonth			= 0;
        int intDate				= 0;
        String strYear_Err="1";
        String strMonth_Err="1";
        String strDate_Err="1";
        String result;


        //长度、数字类型及空检查
        if (strYear==null || strYear.length () != 4 || strYear.equals("") || IsNum(strYear)==false){
            strYear_Err="0";
        }else{
            intYear  = Integer.valueOf (strYear).intValue ();
            if(intYear==0) strYear_Err="0";
        }
        if (strMonth==null || strMonth.length () > 2 || strMonth.equals("") || IsNum(strMonth)==false){
            strMonth_Err="0";
        }else{
            intMonth = Integer.valueOf (strMonth).intValue ();
            if (intMonth < 1 || intMonth > 12) strMonth_Err="0";
        }
        if (strDate==null || strDate.length () > 2 || strDate.equals("") || IsNum(strDate)==false){
            strDate_Err="0";
        }else{
            intDate  = Integer.valueOf (strDate).intValue ();
            if (intDate < 1 || intDate > 31) strDate_Err="0";
        }

        if(strMonth_Err.equals("1") && strDate_Err.equals("1")){
            switch(intMonth){
                case 4:
                case 6:
                case 9:
                case 11:
                    if (intDate > 30) strDate_Err="0";
                    break;
                case 2:
                    GregorianCalendar GreDate = new GregorianCalendar();
                    if (GreDate.isLeapYear (intYear)){
                        if (intDate > 29) strDate_Err="0";
                    }else{
                        if (intDate > 28) strDate_Err="0";
                    }
                    break;
            }
        }
        result=strYear_Err+strMonth_Err+strDate_Err;
        System.out.println(result);
        return result;

    }

    /*****************************************************<BR>
     * 函数名:	IsNum   					              <BR>
     * 机能概要:		判断是否全为数字							<BR>
     *                                                     <BR>
     * 参数:	strin								        <BR>
     * 返回值:	True	全为数字								<BR>
     *			False	不全为数字							<BR>
     *********************************************************/
    public static boolean IsNum(String strin)
    {
        char c;
        for( int i=0 ; i<strin.length() ; i++ ){
            c = strin.charAt (i);
            if (( c <= 0x0039 && c >= 0x0030 ) == false)
                return false;
        }
        return true;

    }

    /**
     * 检查日期类型(YYYY/MM/DD)
     * @return CbpDate
     */
    public Calendar checkDate(String verDate, int type) {
        try {
            System.out.println("[CommonCheck]:checkDate START");
            int pos = 0;
            String fmtStr = "";
            String str = verDate.trim();
            if (type == 0) {
                if (str.length() > 10 || str.length() < 8) {
                    return null;
                }
            } else if (type == 1) {
                if (str.length() > 7 || str.length() < 6) {
                    return null;
                }
            }
            pos = str.indexOf("/");
            if (pos != 4) {
                return null;
            }
            for (int i = 0; i < 2; i++) {
                pos = str.indexOf("/0");
                if (pos > 0) {
                    str = str.substring(0, pos + 1) + str.substring(pos + 2);
                }
            }
            if (type == 0) {
                fmtStr = "yyyy/M/d";
            } else if (type == 1) {
                fmtStr = "yyyy/M";
            }
            SimpleDateFormat df = new SimpleDateFormat(fmtStr);
            Date vd = df.parse(str);
            String newStr = df.format(vd);
            Calendar c = Calendar.getInstance();
            if (newStr.equals(str)) {
                System.out.println("[CommonCheck]:checkDate END");
                c.setTime(vd);
                return c;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查日期相差一个月
     * @return boolean
     */
    public boolean minusMonth(String startStr, String endStr) {
        try {
            System.out.println("[CommonCheck]:minusMonth START");
            Calendar startd = checkDate(startStr, 0);
            Calendar endd = checkDate(endStr, 0);
            if (startd != null && endd != null) {
                if (startd.after(endd)) {
                    return false;
                }
                int mon = startd.get(Calendar.MONTH);
                startd.add(Calendar.MONTH,1);
                if (startd.after(endd) && (endd.get(Calendar.MONTH) - mon < 2)) {
                    System.out.println("[CommonCheck]:minusMonth END");
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Load *.properties file
     *
     * @throws FileNotFoundException
     * @throws IOException
     * @return Properties
     */
    @SuppressWarnings({ "unchecked", "resource","rawtypes" })
    public List readFile(String fileAllName) {
        File file = new File(fileAllName);
        BufferedReader bufferedReader = null;
        List list = Collections.synchronizedList(new ArrayList());
        try {

            FileInputStream in = new FileInputStream(file);
            CsvReader csvReader = new CsvReader(in, Charset.forName("GB2312"));
            // 读表头
//			csvReader.readHeaders();
            String str = "";
            String strLine = "";
            // 获取正则表达式
            String regExp = getRegExp();
            while (csvReader.readRecord()){
                strLine=csvReader.getRawRecord();
                strLine = strLine.replace("\\N","");
                if (!strLine.trim().equals("")) {
                    // 匹配每个字段项
                    Pattern pattern = Pattern.compile(regExp);
                    Matcher matcher = pattern.matcher(strLine
                            .trim());
                    List listTemp = new ArrayList();
                    // 读取行记录的各个字段值
                    while (matcher.find()) {
                        str = matcher.group();
                        str = str.trim();
                        if (str.endsWith(",")) {
                            str = str
                                    .substring(0, str.length() - 1);
                            str = str.trim();
                        }
                        if (str.startsWith("\"")
                                && str.endsWith("\"")) {
                            str = str
                                    .substring(1, str.length() - 1);
                            if (isExisted("\"\"", str)) {
                                str = str.replaceAll("\"\"", "\"");
                            }
                        }
                        // 将字段值存入list
                        listTemp.add(str);
                    }
                    // 删除最后空白
                    listTemp.remove(listTemp.size() - 1);
                    // 将行记录存入list
                    list.add((String[]) listTemp
                            .toArray(new String[listTemp.size()]));
                }
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }
        return list;
    }
    /**
     * 获取正则表达式
     *
     * @return
     */
    private String getRegExp() {

        String SPECIAL_CHAR_A = "[^\",\\n  ]";
        String SPECIAL_CHAR_B = "[^\",\\n]";
        String strRegExp = "";
        strRegExp = "\"((" + SPECIAL_CHAR_A + "*[,\\n  ])*(" + SPECIAL_CHAR_A
                + "*\"{2})*)*" + SPECIAL_CHAR_A + "*\"[  ]*,[  ]*" + "|"
                + SPECIAL_CHAR_B + "*[  ]*,[  ]*" + "|\"((" + SPECIAL_CHAR_A
                + "*[,\\n  ])*(" + SPECIAL_CHAR_A + "*\"{2})*)*"
                + SPECIAL_CHAR_A + "*\"[  ]*" + "|" + SPECIAL_CHAR_B + "*[  ]*";
        return strRegExp;
    }
    /**
     * 校验字符串是否存在
     *
     * @param argChar
     * @param argStr
     * @return
     */
    private boolean isExisted(String argChar, String argStr) {

        boolean blnReturnValue = false;
        if ((argStr.indexOf(argChar) >= 0)
                && (argStr.indexOf(argChar) <= argStr.length())) {
            blnReturnValue = true;
        }
        return blnReturnValue;
    }

    /**
     * 获取字符长度
     *
     * @param s
     * @return
     */
    public static int getWordCountRegex(String s) {
        s = s.replaceAll("[^\\x00-\\xff]", "**");
        int length = s.length();
        return length;
    }
}

 

posted @ 2023-03-08 09:11  Power_Gives  阅读(32)  评论(0)    收藏  举报