随笔-26  评论-13  文章-46  trackbacks-0
在J2EE项目开发中使用到的一些自己写的基本函数

package jing.tools;

import java.util.*;
import java.text.*; //日期处理用到的包
import java.util.regex.*;
import java.lang.*;

/**
* <p>Title: 常用基础函数</p>
* <p>Description: 以下全部是静态函数</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: 静靖工作室</p>
* “@deprecated Method 方法名 is deprecated” 在方法的注释里加上此注释,表示此方法以后版本不再被支持。
* 文件注释只能写在import后,类定义前才能在javadoc中出现文件的注释
* @author 欧朝敬 QQ:35712069
* @version 1.0
*/
public class BaseFunction {
    public BaseFunction() {

    }

    /**
     * 拼合一维数组为字符串。
     * <B>拆分字串按指定字符分解到一维数组使用String类的split(String regex)</B>
     * @param param String[] 数组
     * @param spilt String 字符串之单的分离符
     * @return String
     */
    public static String arrayToString(String[] param, String spilt) {
        String rentunstring;
        StringBuffer tempstr = new StringBuffer();
        int len = param.length;
        for (int i = 0; i < len - 1; i++) {
            tempstr.append(param);
            tempstr.append(spilt);
        }
        tempstr.append(param[len - 1]);
        rentunstring = tempstr.toString();
        return rentunstring;
    }

    /**
     * 产生在start和end之间的num个随机整数,返回值存在HashMap中。
     * 示例
     * HashMap hm=BaseFunction.random(1,100,5);
     * Set set=hm.keySet();
     * Iterator it=set.iterator();
     * while(it.hasNext()){
     *     System.out.println(hm.get(it.next()));
     * }
     * @param start int 起始点
     * @param end int 结束点
     * @param num int 生成个数
     * @return HashMap
     */
    public static HashMap random(int start, int end, int num) {
        HashMap hashMap = new HashMap();
        for (int i = 0; i < num; i++) {
            double sru = Math.random() * end;
            int tag = Math.round((float) sru);
            if (tag < start) {
                i--;
            } else {
                hashMap.put(new Integer(i), new Integer(tag));
            }
        }
        return hashMap;
    }


    /**
     * 获取当前时间,返回时间格式(如果调用参数为true时返回yyyy-MM-dd HH:mm:ss
     * ,否则为false时返回yyyy-MM-DD不带日期格式)
     * @param time boolean
     * @return String
     * @throws Exception
     */
    public static String getNowTime(boolean time) throws java.lang.Exception {
        Date now = new Date();
        String format = "";
        //yyyy-MM-dd HH:mm:ss:S 年月日时分秒毫杪
        if (time) {
            format = "yyyy-MM-dd HH:mm:ss";
        } else {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String nowtime = sdf.format(now);
        return nowtime;
    }

    /**
     * 将HashMap内容转入数组,
     * 示例
     *    HashMap hashMap = new HashMap();
     *    hashMap.put("ka", "bb");
     *    hashMap.put("kb", "cc");
     *    hashMap.put("jk", "fdsaf");
     *    hashMap.put("ak", "kkkkk");
     *    Object[] obj = BaseFunction.hashMapToArray(hashMap);
     *    for (int i = 0; i < obj.length; i++) {
     *        System.out.println(obj);
     *    }
     * @param param HashMap
     * @return Object[]
     */
    public static Object[] hashMapToArray(HashMap param) {
        int size = param.size();
        if (param == null || param.size() == 0) {
            return null;
        }
        Object[] obj = new Object[size];
        Set set = param.keySet();
        Iterator ite = set.iterator();
        for (int i = 0; ite.hasNext(); i++) {
            obj = param.get(ite.next());
        }
        return obj;
    }

    /**
     * 日期转字符串
     * 示例:dateToString(stringToDate("2005-5-2 0:0:10"));
     * @param date Date
     * @return String
     * 返回字符串格式为“yyyy年MM月dd日 HH时mm分ss秒”或“yyyy年MM月dd日”
     * 根据输入的日期是否含有时间来确定输出格式
     */
    public static String dateToString(Date date) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"),
                                                 Locale.CHINA);
        calendar.clear();
        calendar.setTimeInMillis(date.getTime());
        String format = "";

        /*        if (calendar.get(Calendar.MILLISECOND) == 0 &&
                    calendar.get(Calendar.SECOND) == 0 &&
         calendar.get(Calendar.SECOND) == calendar.get(Calendar.MINUTE) &&
         calendar.get(Calendar.MINUTE) == calendar.get(Calendar.HOUR)) {
                    format = "yyyy'年'MM'月'dd'日'";
                } else {
                 format = "yyyy'年'MM'月'dd'日' HH'时'mm'分'ss'秒'";
                }
         */
        format = "yyyy'年'MM'月'dd'日' HH'时'mm'分'ss'秒'";
        String return_string = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        //yyyy-MM-dd HH:mm:ss:S 年月日时分秒毫杪
        return_string = sdf.format(date);
        return return_string;
    }

    /**
     * 字符串转日期
     * 示例:stringToDate("2005-5-2 0:0:10");
     * @param str String
     * 输入字符串日期可用三种格式
     * yyyy-MM-dd HH:mm:ss完整式
     * yyyy-MM-dd HH:mm不含秒
     * yyyy-MM-dd只有日期不含时间
     * @return Date
     * @throws Exception
     */
    public static Date stringToDate(String str) throws Exception {
        Date return_date = null;
        String format = "";
        if (str.length() > 13) {
            format = "yyyy-MM-dd HH:mm:ss";
        } else if (str.length() > 10) {
            format = "yyyy-MM-dd HH:mm";
        } else {
            format = "yyyy-MM-dd";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return_date = sdf.parse(str);
        } catch (ParseException e) {
            throw new Exception(
                    "输入字符串的格式出错(格式为yyyy-MM-dd/yyyy-MM-dd HH:mm/yyyy-MM-dd HH:mm:ss):" +
                    e.getMessage());
        }
        return return_date;
    }

    /**
     * 连续产生指定个数的字符串
     * @param str String
     * @param count int
     * @return String
     */
    public static String continuousMakeString(String str, int count) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < count; i++) {
            sb.append(str);
        }
        return (sb.toString());
    }

    /**
     * 将字符串开头的所有空格替换成指定的字符
     * 在JSP中经常用到把字符串开头的n个空格替换成n个&nbsp;字符
     * 就可以使用此函数调用示例
     * replaceStartsWithSpace("  中国  湖南  长沙","&nbsp;");结果为“&nbsp;&nbsp;中国  湖南  长沙”
     * @param str String
     * @param sub String
     * @return String
     */
    public static String replaceStartsWithSpace(String str, String sub) {
        String returnStr = "";
        String regEx = "\\S"; //非空格字符
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(str);
        matcher.find();
        int start = matcher.start(); //非空格开始的位置
        for (int i = 0; i < start; i++) {
            returnStr = returnStr + sub;
        }
        returnStr = returnStr + str.substring(start);
        return returnStr;
    }

    /**
     * 查找指定的元素是否存在于元素数组中
     * 使用Object支持各种对象数组
     * 示例
     * String[] des = {"ada", "ss", "dd","aa"};
     * System.out.println(BaseFunction.contains(str, "adfab"));
     * @param objArray Object[]
     * @param value Object
     * @return int 如果查到则返回第一次在数组中出现的下标值,查不到则返回值为-1
     */
    public static int contains(Object[] objArray, Object value) {
        int j = -1;
        for (int i = 0; i < objArray.length; i++) {
            if (objArray.equals(value)) { //查到则返回下标
                j = i;
                break;
            }
        }
        return j;
    }

    /**
     * 字符串数组中是否包含指定的字符串。
     * @param strings 字符串数组
     * @param string 字符串
     * @param caseSensitive 是否大小写敏感(true区分大小写,false不区分大小写)
     * @return 包含时返回true,否则返回false
     * @since  0.4
     */
    public static boolean contains(String[] strings, String string,
                                   boolean caseSensitive) {
        for (int i = 0; i < strings.length; i++) {
            if (caseSensitive == true) {
                if (strings.equals(string)) {
                    return true;
                }
            } else {
                if (strings.equalsIgnoreCase(string)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 数组拷贝,建议使用System.arraycopy()速度更快,把source数据内容拷贝到destination中
     * 使用Object则支持多种对象数组
     * 示例
     * String[] des = {"ada", "ss", "dd","aa"};
     * String[] src = new String[8];
     * BaseFunction.copy(des, src);
     * @param source Object[]
     * @param destination Object[]
     */
    public static void copy(Object[] source, Object[] destination) {
        if (destination == null || source == null) {
            throw new java.lang.NullPointerException("数组没有初始化!");
        }
        if (destination.length < source.length) {
            throw new java.lang.ArrayIndexOutOfBoundsException("两数组长度不相等!");
        }
        for (int i = 0; i < source.length; i++) {
            destination = source;
        }
    }

    /**
     * 去除数组中的重复元素,调用示例
     * String[] src = {"dafdfad", "asdfasdf", "dafdfad", "adfasdf", "dafdfad","dafdfad"};
     * Object[] test =BaseFunction.wipeOffRepeat(src);
     * @param objArray Object[]
     * @return Object[]
     */
    public static Object[] wipeOffRepeat(Object[] objArray) {
        Object[] obj = null;
        ArrayList list = new ArrayList();
        for (int i = 0; i < objArray.length; i++) {
            list.add(objArray);
        }
        //去除list中的重复对象
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        obj = list.toArray();
        return obj;
    }

    /**
     * 四舍五入
     * @param param double 要进行四舍五入的值
     * @param num int 保留的小数位数
     * @return double
     */
    public static double round(double param, int num) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(num);
        double returndouble = Double.parseDouble(nf.format(param));
        return returndouble;
    }

    /**
     * 主函数做测试用
     * @param args String[]
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        /*        System.out.println(BaseFunction.dateToString(stringToDate(
                        "2005-5-2 0:0:10")));
                System.out.println(BaseFunction.getTime(true));
                System.out.println(BaseFunction.continuousMakeString(" ", 10));
                System.out.println(BaseFunction.replaceStartsSpace(
                        " fadsfas   dfsd", "&nbsp;"));
         */
        /*        HashMap hm=BaseFunction.random(1,100,5);
                Set set=hm.keySet();
                Iterator it=set.iterator();
                while(it.hasNext()){
                    System.out.println(hm.get(it.next()));
                }
         */
        //System.out.println(BaseFunction.replaceStartsWithSpace("  中国  湖南  长沙","&nbsp;"));
        System.out.println(BaseFunction.round(0.25689,2));
    }
}
posted on 2005-08-31 14:05 似水流年 阅读(420) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: