JAVA常用函数5

import java.io.*

public class MyUtil{ 
    
public static String big5ToUnicode(String s){ 
        
try
            
return new String(s.getBytes("ISO8859_1"), "Big5"); 
        } 
        
catch (UnsupportedEncodingException uee){ 
            
return s; 
        } 
    } 

    
public static String UnicodeTobig5(String s){ 
        
try
            
return new String(s.getBytes("Big5"), "ISO8859_1"); 
        } 
        
catch (UnsupportedEncodingException uee){ 
            
return s; 
        } 
    } 

    
public static String toHexString(String s){ 
        String str
=""
        
for (int i=0; i <s.length(); i++){ 
            
int ch=(int)s.charAt(i); 
            String s4
="0000"+Integer.toHexString(ch); 
            str
=str+s4.substring(s4.length()-4)+" "
        } 
        
return str; 
    } 


/** 
* 取得服务器当前的各种具体时间 
* 回车:日期时间 
*/ 

import java.util.*

public class GetNowDate{ 
    Calendar  calendar 
= null
  
    
public GetNowDate(){ 
        calendar 
= Calendar.getInstance(); 
        calendar.setTime(
new Date()); 
    } 
  
    
public int getYear(){ 
        
return calendar.get(Calendar.YEAR); 
    } 
  
    
public int getMonth(){ 
        
return 1 + calendar.get(Calendar.MONTH); 
    } 
  
    
public int getDay(){ 
        
return calendar.get(Calendar.DAY_OF_MONTH); 
    } 
  
    
public int getHour(){ 
        
return calendar.get(Calendar.HOUR_OF_DAY); 
    } 
    
    
public int getMinute(){ 
        
return calendar.get(Calendar.MINUTE); 
    } 
  
    
public int getSecond(){ 
        
return calendar.get(Calendar.SECOND); 
    } 
    
    
public String getDate(){ 
        
return getMonth()+"/"+getDay()+"/"+getYear(); 
    } 
  
    
public String getTime(){ 
        
return getHour()+":"+getMinute()+":"+getSecond(); 
    } 
  
    
public String getDate2(){ 
        String yyyy
="0000", mm="00", dd="00"
        yyyy 
= yyyy + getYear(); 
        mm  
= mm  + getMonth(); 
        dd  
= dd + getDay(); 
        yyyy 
= yyyy.substring(yyyy.length()-4); 
        mm  
= mm.substring(mm.length()-2); 
        dd  
= dd.substring(dd.length()-2); 
        
return yyyy + "/" + mm + "/" +  dd; 
    } 
  
    
public String getTime2(){ 
        String hh
="00", mm="00", ss="00"
        hh 
= hh + getHour(); 
        mm 
= mm + getMinute(); 
        ss 
= ss + getSecond(); 
        hh 
= hh.substring(hh.length()-2, hh.length()); 
        mm 
= mm.substring(mm.length()-2, mm.length()); 
        ss 
= ss.substring(ss.length()-2, ss.length()); 
        
return hh + ":" + mm + ":" + ss; 
    } 



中文乱码转换 
public String china(String args){ 
    String s 
= null
    String s 
= new String(args.getBytes("ISO-8859-1"), "gb2312"); 
    
return s; 
}


 
/**
   * 替换字符串
   * 
   * 
@param from String 原始字符串
   * 
@param to String 目标字符串
   * 
@param source String 母字符串
   * 
@return String 替换后的字符串
   
*/
  
public static String replace(String from, String to, String source) {
    
if (source == null || from == null || to == null)
      
return null;
    StringBuffer bf 
= new StringBuffer("");
    
int index = -1;
    
while ((index = source.indexOf(from)) != -1) {
      bf.append(source.substring(
0, index) + to);
      source 
= source.substring(index + from.length());
      index 
= source.indexOf(from);
    }
    bf.append(source);
    
return bf.toString();
  }


    
/**
     * Description: 获取GMT8时间
     * 
@return 将当前时间转换为GMT8时区后的Date
     
*/
    
public static Date getGMT8Time(){
        Date gmt8 
= null;
        
try {
            Calendar cal 
= Calendar.getInstance(TimeZone.getTimeZone("GMT+8"),Locale.CHINESE);
            Calendar day 
= Calendar.getInstance();
            day.set(Calendar.YEAR, cal.get(Calendar.YEAR));
            day.set(Calendar.MONTH, cal.get(Calendar.MONTH));
            day.set(Calendar.DATE, cal.get(Calendar.DATE));
            day.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
            day.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
            day.set(Calendar.SECOND, cal.get(Calendar.SECOND));
            gmt8 
= day.getTime();
        } 
catch (Exception e) {
            System.out.println(
"获取GMT8时间 getGMT8Time() error !");
            e.printStackTrace();
            gmt8 
= null;
        }
        
return  gmt8;
    }

处理特殊符号的工具类,这个类是从sturts源码里挖出来的 
/**
 * DealingCharacter.java
 * Description: 
 * 
@author li.b
 * 
@version 2.0
 * Jun 27, 2008
 
*/
public class DealingCharacter {

    
/**
     * Description: 转译特殊符号标签
     * 
@param value 需要处理的字符串
     * 
@return 
     
*/
     
public static String filter(String value)
        {
            
if(value == null || value.length() == 0)
                
return value;
            StringBuffer result 
= null;
            String filtered 
= null;
            
for(int i = 0; i < value.length(); i++)
            {
                filtered 
= null;
                
switch(value.charAt(i))
                {
                
case 60// '<'
                    filtered = "&lt;";
                    
break;

                
case 62// '>'
                    filtered = "&gt;";
                    
break;

                
case 38// '&'
                    filtered = "&amp;";
                    
break;

                
case 34// '"'
                    filtered = "&quot;";
                    
break;

                
case 39// '\''
                    filtered = "&#39;";
                    
break;
                }
                
if(result == null)
                {
                    
if(filtered != null)
                    {
                        result 
= new StringBuffer(value.length() + 50);
                        
if(i > 0)
                            result.append(value.substring(
0, i));
                        result.append(filtered);
                    }
                } 
else
                
if(filtered == null)
                    result.append(value.charAt(i));
                
else
                    result.append(filtered);
            }

            
return result != null ? result.toString() : value;
        }

     
public static void main(String[] args) {
         System.out.println(DealingCharacter.filter(
"<HTML>sdfasfas</HTML>"));
    }
}

//四舍五入方法
MathContext v = new MathContext(5,RoundingMode.HALF_DOWN);
BigDecimal a 
= new BigDecimal("0.87234643298346",v);

正则表达式用于字符串处理、表单验证等场合,实用高效。现将一些常用的表达式收集于此,以备不时之需。 

匹配中文字符的正则表达式: [\u4e00
-\u9fa5] 
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了 

匹配双字节字符(包括汉字在内):[
^\x00-\xff] 
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) 

匹配空白行的正则表达式:\n\s
*\r 
评注:可以用来删除空白行 

匹配HTML标记的正则表达式: 
<(\S*?)[^>]*>.*? </\1>| <.*? /> 
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力 

匹配首尾空白字符的正则表达式:
^\s*|\s*
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式 

匹配Email地址的正则表达式:\w
+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 
评注:表单验证时很实用 

匹配网址URL的正则表达式:[a
-zA-z]+://[^\s]* 
评注:网上流传的版本功能很有限,上面这个基本可以满足需求 

匹配帐号是否合法(字母开头,允许5
-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 
评注:表单验证时很实用 

匹配国内电话号码:\d{
3}-\d{8}|\d{4}-\d{7
评注:匹配形式如 
0511-4405222 或 021-87888822 

匹配腾讯QQ号:[
1-9][0-9]{4,} 
评注:腾讯QQ号从10000开始 

匹配中国邮政编码:[
1-9]\d{5}(?!\d) 
评注:中国邮政编码为6位数字 

匹配身份证:\d{
15}|\d{18
评注:中国的身份证为15位或18位 

匹配ip地址:\d
+\.\d+\.\d+\.\d+ 
评注:提取ip地址时有用 

匹配特定数字: 
^[1-9]\d*$    //匹配正整数 
^-[1-9]\d*$   //匹配负整数 
^-?[1-9]\d*$   //匹配整数 
^[1-9]\d*|0$  //匹配非负整数(正整数 + 0) 
^-[1-9]\d*|0$   //匹配非正整数(负整数 + 0) 
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$   //匹配正浮点数 
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$  //匹配负浮点数 
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$  //匹配浮点数 
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$   //匹配非负浮点数(正浮点数 + 0) 
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$  //匹配非正浮点数(负浮点数 + 0) 
评注:处理大量数据时有用,具体应用时注意修正 

匹配特定字符串: 
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串 
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串 
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串 
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串 
^\w+$  //匹配由数字、26个英文字母或者下划线组成的字符串 
评注:最基本也是最常用的一些表达式 

/**
     * 将数组转成字符串 在调试或记录日志时用到
     * 
     * 
@param array
     * 
@return
     
*/
    
public static String byte2string(byte[] array) {
        StringBuilder sb 
= new StringBuilder();

        sb.append(
"Length " + array.length + " Content ");
        
        
for (int i = 0; i < leng; i++) {
            sb 
= sb.append(String.format("%02X", array[i])).append(":");
        }
        
int ind = sb.lastIndexOf(":");
        sb.delete(ind, ind 
+ 1);
        
return sb.toString();
    }

/**
     * 对字节流进行GBK解码
     * 
     * 
@param byteBuffer
     * 
@return
     
*/
    
public static String decode(ByteBuffer byteBuffer) {
        Charset charset 
= Charset.forName("ISO-8859-1");
        CharsetDecoder decoder 
= charset.newDecoder();
        
try {
            CharBuffer charBuffer 
= decoder.decode(byteBuffer);
            
return new String(charBuffer.toString().getBytes("ISO8859_1"),
                    
"GBK").trim();
        } 
catch (Exception e) {
            
return null;
        }
    }

import java.util.Arrays;
import java.util.Random;

/**
 * <code>RandomUtil</code> - Random Tool Class.
 * 
@author SageZk
 * 
@version 1.0
 
*/
public class RandomUtil {

    
private RandomUtil() {}

    
private static Random rnd = null;

    
/**
     * 初始化随机数发生器。
     
*/
    
private static void initRnd() {
        
if (rnd == null) rnd = new Random();
    }

    
/**
     * 计算并返回无重复值的以 <code>min</code> 为下限 <code>max</code> 为上限的随机整数数组。
     * 
@param min 随机整数下限(包含)
     * 
@param max 随机整数上限(包含)
     * 
@param len 结果数组长度
     * 
@return 结果数组
     
*/
    
public static int[] getLotteryArray(int min, int max, int len) {
        
//参数校验及性能优化
        if (len < 0return null;  //长度小于 0 的数组不存在
        if (len == 0return new int[0];  //返回长度为 0 的数组
        if (min > max) {  //校正参数 min max
            int t = min;
            min 
= max;
            max 
= t;
        }
        
final int LEN = max - min + 1;  //种子个数
        if (len > LEN) return null;  //如果出现 35 选 36 的情况就返回 null
        
//计算无重复值随机数组
        initRnd();  //初始化随机数发生器
        int[] seed = new int[LEN];  //种子数组
        for (int i = 0, n = min; i < LEN;) seed[i++= n++;  //初始化种子数组
        for (int i = 0, j = 0, t = 0; i < len; ++i) {
            j 
= rnd.nextInt(LEN - i) + i;
            t 
= seed[i];
            seed[i] 
= seed[j];
            seed[j] 
= t;
        }
        
return Arrays.copyOf(seed, len);  //注意:copyOf 需要 JRE1.6
    }

    
//Unit Testing
    public static void main(String[] args) {
        
final int N = 10000;  //测试次数
        for (int i = 0; i < N; ++i) {
            
int[] la = RandomUtil.getLotteryArray(1357);
            
if (la == nullcontinue;
            
for (int v : la) System.out.printf("%0$02d ", v);
            System.out.println();
        }
    }

}

/*
操作属性文件,可以为我们的程序带来更方便的移植性,下面是一个示例,可以读、写、更改属性
读采用了两种方式,一种是采用Properties类,另外一种是采用资源绑定类ResourceBundle类,
下面是源程序,里面有详细的注释:
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
/**
 *对属性文件(xx.properties)的操作
 *注:属性文件一定要放在当前工程的根目录下,也就是放在与src目录在同一个目录下(我的JDevelop
 *是这样的)
 
*/
public class OperatePropertiesFile {
    
public OperatePropertiesFile() {
    }
    
/**
     *采用Properties类取得属性文件对应值
     *@parampropertiesFileNameproperties文件名,如a.properties
     *@parampropertyName属性名
     *@return根据属性名得到的属性值,如没有返回""
     
*/
    
public static String getValueByPropertyName(String propertiesFileName,String propertyName) {
        String s
="";
        Properties p
=new Properties();//加载属性文件读取类
        FileInputStream in;
        
try {
            
//propertiesFileName如test.properties
            in = new FileInputStream(propertiesFileName);//以流的形式读入属性文件
            p.load(in);//属性文件将该流加入的可被读取的属性中
            in.close();//读完了关闭
            s=p.getProperty(propertyName);//取得对应的属性值
        } catch (Exception e) {
            e.printStackTrace();
        }
        
return s;
    }
    
/**
     *采用ResourceBundel类取得属性文件对应值,这个只能够读取,不可以更改及写新的属性
     *@parampropertiesFileNameWithoutPostfixproperties文件名,不带后缀
     *@parampropertyName属性名
     *@return根据属性名得到的属性值,如没有返回""
     
*/
    
public static String getValueByPropertyName_(String propertiesFileNameWithoutPostfix,String propertyName) {
        String s
="";
        
//如属性文件是test.properties,那此时propertiesFileNameWithoutPostfix的值就是test
        ResourceBundle bundel = ResourceBundle.getBundle(propertiesFileNameWithoutPostfix);
        s
=bundel.getString(propertyName);
        
return s;
    }
    
/**
     *更改属性文件的值,如果对应的属性不存在,则自动增加该属性
     *@parampropertiesFileNameproperties文件名,如a.properties
     *@parampropertyName属性名
     *@parampropertyValue将属性名更改成该属性值
     *@return是否操作成功
     
*/
    
public static boolean changeValueByPropertyName(String propertiesFileName,String propertyName,String propertyValue) {
        
boolean writeOK=true;
        Properties p
=new Properties();
        InputStream in;
        
try {
            
            in 
= new FileInputStream(propertiesFileName);
            p.load(in);
//
            in.close();
            p.setProperty(propertyName,propertyValue);
//设置属性值,如不属性不存在新建
            
//p.setProperty("testProperty","testPropertyValue");
            FileOutputStream out=new FileOutputStream(propertiesFileName);//输出流
            p.store(out,"");//设置属性头,如不想设置,请把后面一个用""替换掉
            out.flush();//清空缓存,写入磁盘
            out.close();//关闭输出流
        } catch (Exception e) {
            e.printStackTrace();
        }
        
return writeOK;
    }
}



posted @ 2009-10-09 23:16  angushine  阅读(301)  评论(0编辑  收藏  举报