空间站

北极心空

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  15 Posts :: 393 Stories :: 160 Comments :: 0 Trackbacks

 

/**  
    * 将某个日期以固定格式转化成字符串  
    *   
    * 
@param date  
    * 
@return String  
    
*/  
   
public static String dateToStr(java.util.Date date)   
   {   
       SimpleDateFormat sdf 
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
       String str 
= sdf.format(date);   
       
return str;   
   }  

/**  
 * 判断任意一个整数是否素数  
 *   
 * 
@param n  
 * 
@return boolean  
 
*/  
public static boolean isPrimes(int n)   
{   
    
for (int i = 2; i <= Math.sqrt(n); i++)   
    {   
        
if (n % i == 0)   
        {   
            
return false;   
        }   
    }   
    
return true;   
}  
/**  
 * 获得任意一个整数的阶乘,递归  
  *   
 * 
@param n  
 * 
@return n!  
 
*/  
public static int factorial(int n)   
{   
    
if (n == 1)   
    {   
        
return 1;   
    }   
    
return n * factorial(n - 1);   
}  
/**  
 * 将指定byte数组以16进制的形式打印到控制台  
  *   
 * 
@param hint String  
 * 
@param b byte[]              
 * 
@return void   
 
*/  
public static void printHexString(String hint, byte[] b)   
{   
    System.out.print(hint);   
    
for (int i = 0; i < b.length; i++)   
    {   
        String hex 
= Integer.toHexString(b[i] & 0xFF);   
        
if (hex.length() == 1)   
        {   
            hex 
= '0' + hex;   
        }   
        System.out.print(hex.toUpperCase() 
+ " ");   
    }   
    System.out.println(
"");   
}  

常用的java函数(二) 常用字符串处理
 /**  
   * 分割字符串  
   *   
   * 
@param str String 原始字符串  
   * 
@param splitsign String 分隔符  
   * 
@return String[] 分割后的字符串数组  
   
*/  
  
public static String[] split(String str, String splitsign) {   
    
int index;   
    
if (str == null || splitsign == null)   
      
return null;   
    ArrayList al 
= new ArrayList();   
    
while ((index = str.indexOf(splitsign)) != -1) {   
      al.add(str.substring(
0, index));   
      str 
= str.substring(index + splitsign.length());   
    }   
    al.add(str);   
    
return (String[]) al.toArray(new String[0]);   
  }   
  
  
/**  
   * 替换字符串  
   *   
   * 
@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();   
  }   
  
  
/**  
   * 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)  
   *   
   * 
@param str String 原始字符串  
   * 
@return String 替换后的字符串  
   
*/  
  
public static String htmlencode(String str) {   
    
if (str == null) {   
      
return null;   
    }   
  
    
return replace("\"""&quot;", replace("<""&lt;", str));   
  }   
  
  
/**  
   * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)  
   *   
   * 
@param str String  
   * 
@return String  
   
*/  
  
public static String htmldecode(String str) {   
    
if (str == null) {   
      
return null;   
    }   
  
    
return replace("&quot;""\"", replace("&lt;""<", str));   
  }   
  
  
private static final String _BR = "<br/>";   
  
  
/**  
   * 在页面上直接显示文本内容,替换小于号,空格,回车,TAB  
   *   
   * 
@param str String 原始字符串  
   * 
@return String 替换后的字符串  
   
*/  
  
public static String htmlshow(String str) {   
    
if (str == null) {   
      
return null;   
    }   
  
    str 
= replace("<""&lt;", str);   
    str 
= replace(" ""&nbsp;", str);   
    str 
= replace("\r\n", _BR, str);   
    str 
= replace("\n", _BR, str);   
    str 
= replace("\t""&nbsp;&nbsp;&nbsp;&nbsp;", str);   
    
return str;   
  }   
  
  
/**  
   * 返回指定字节长度的字符串  
   *   
   * 
@param str String 字符串  
   * 
@param length int 指定长度  
   * 
@return String 返回的字符串  
   
*/  
  
public static String toLength(String str, int length) {   
    
if (str == null) {   
      
return null;   
    }   
    
if (length <= 0) {   
      
return "";   
    }   
    
try {   
      
if (str.getBytes("GBK").length <= length) {   
        
return str;   
      }   
    } 
catch (Exception ex) {   
    }   
    StringBuffer buff 
= new StringBuffer();   
  
    
int index = 0;   
    
char c;   
    length 
-= 3;   
    
while (length > 0) {   
      c 
= str.charAt(index);   
      
if (c < 128) {   
        length
--;   
      } 
else {   
        length
--;   
        length
--;   
      }   
      buff.append(c);   
      index
++;   
    }   
    buff.append(
"");   
    
return buff.toString();   
  }   
  
  
/**  
   * 判断是否为整数  
   *   
   * 
@param str 传入的字符串  
   * 
@return 是整数返回true,否则返回false  
   
*/  
  
public static boolean isInteger(String str) {   
    Pattern pattern 
= Pattern.compile("^[-\\+]?[\\d]*$");   
    
return pattern.matcher(str).matches();   
  }   
  
  
/**  
   * 判断是否为浮点数,包括double和float  
   *   
   * 
@param str 传入的字符串  
   * 
@return 是浮点数返回true,否则返回false  
   
*/  
  
public static boolean isDouble(String str) {   
    Pattern pattern 
= Pattern.compile("^[-\\+]?[.\\d]*$");   
    
return pattern.matcher(str).matches();   
  }   
  
  
/**  
   * 判断输入的字符串是否符合Email样式.  
   *   
   * 
@param str 传入的字符串  
   * 
@return 是Email样式返回true,否则返回false  
   
*/  
  
public static boolean isEmail(String str) {   
    Pattern pattern 
= Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");   
    
return pattern.matcher(str).matches();   
  }   
  
  
/**  
   * 判断输入的字符串是否为纯汉字  
   *   
   * 
@param str 传入的字符窜  
   * 
@return 如果是纯汉字返回true,否则返回false  
   
*/  
  
public static boolean isChinese(String str) {   
    Pattern pattern 
= Pattern.compile("[\u0391-\uFFE5]+$");   
    
return pattern.matcher(str).matches();   
  }   
  
  
/**  
   * 是否为空白,包括null和""  
   *   
   * 
@param str  
   * 
@return  
   
*/  
  
public static boolean isBlank(String str) {   
    
return str == null || str.trim().length() == 0;   
  }   
  
  
/**  
   * 判断是否为质数  
   *   
   * 
@param x  
   * 
@return  
   
*/  
  
public static boolean isPrime(int x) {   
    
if (x <= 7) {   
      
if (x == 2 || x == 3 || x == 5 || x == 7)   
        
return true;   
    }   
    
int c = 7;   
    
if (x % 2 == 0)   
      
return false;   
    
if (x % 3 == 0)   
      
return false;   
    
if (x % 5 == 0)   
      
return false;   
    
int end = (int) Math.sqrt(x);   
    
while (c <= end) {   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 4;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 2;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 4;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 2;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 4;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 6;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 2;   
      
if (x % c == 0) {   
        
return false;   
      }   
      c 
+= 6;   
    }   
    
return true;   
  }   
    
/**  
     * 全角字符转半角字符  
     *   
     * 
@param QJStr  
     * 
@return String  
     
*/  
    
public static final String QJToBJChange(String QJStr)   
    {   
        
char[] chr = QJStr.toCharArray();   
        String str 
= "";   
        
for (int i = 0; i < chr.length; i++)   
        {   
            chr[i] 
= (char) ((int) chr[i] - 65248);   
            str 
+= chr[i];   
        }   
        
return str;   
    }   
    
/**  
     * 去掉字符串中重复的子字符串  
     *   
     * 
@param str  
     * 
@return String  
     
*/  
    
private static String removeSameString(String str)   
    {   
        Set
<String> mLinkedSet = new LinkedHashSet<String>();   
        String[] strArray 
= str.split(" ");   
        StringBuffer sb 
= new StringBuffer();   
  
        
for (int i = 0; i < strArray.length; i++)   
        {   
            
if (!mLinkedSet.contains(strArray[i]))   
            {   
                mLinkedSet.add(strArray[i]);   
                sb.append(strArray[i] 
+ " ");   
            }   
        }   
        System.out.println(mLinkedSet);   
        
return sb.toString().substring(0, sb.toString().length() - 1);   
      }   
//过滤特殊字符   
public static String encoding(String src){   
        
if (src==null)   
            
return "";   
        StringBuilder result
=new StringBuilder();   
        
if (src!=null){   
            src
=src.trim();   
            
for (int pos=0;pos<src.length();pos++){   
                
switch(src.charAt(pos)){   
                    
case '\"':result.append("&quot;");break;   
                    
case '<':result.append("&lt;");break;   
                    
case '>':result.append("&gt;");break;   
                    
case '\'':result.append("&apos;");break;   
                    case '&':result.append("&amp;");break;   
                    
case '%':result.append("&pc;");break;   
                    
case '_':result.append("&ul;");break;   
                    
case '#':result.append("&shap;");break;   
                    
case '?':result.append("&ques;");break;   
                    
default:result.append(src.charAt(pos));break;   
                }   
            }   
        }   
        
return result.toString();   
    }   
       
//反过滤特殊字符   
    public static String decoding(String src){   
        
if (src==null)   
            
return "";   
        String result
=src;   
        result
=result.replace("&quot;""\"").replace("&apos;""\'");   
        result=result.replace("&lt;""<").replace("&gt;"">");   
        result
=result.replace("&amp;""&");   
        result
=result.replace("&pc;""%").replace("&ul""_");   
        result
=result.replace("&shap;""#").replace("&ques""?");   
        
return result;   
    }   
  
/**   
    *判断任意一个整数是否素数   
    *@paramn   
    *
@return boolean   
    
*/    
    
public boolean isPrimes(int n)    
    {    
      
for (int i = 2; i <= Math.sqrt(n); i++) {    
          
if(n%i==0)    
          {    
              
return false;    
          }    
      }    
      
return true;    
    }   

常用的java函数(三)数据库连接
/* * Db.java  
Created on 2007年8月20日, 上午 8:37  
*/  
import java.io.*;   
import java.sql.*;   
import java.util.Properties;   
public class Db {   
    
private String driver;   
    
private String url;   
    
private String user;   
    
private String password;   
    
private Connection conn;   
    
private Statement stm;   
    
private ResultSet rs;   
    
public Db(){   
        
this("DBConf.properties");   
    }   
    
public Db(String conf) {   
        loadProperties(conf);   
        setConn();   
    }   
    
public Connection getConn(){   
        
return this.conn;   
    }   
  
//handle the properties file to get the informations for connection   
    private void loadProperties(String conf){   
        Properties props 
= new Properties();   
        
try {   
            props.load(
new FileInputStream(conf));   
        } 
catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } 
catch (IOException e) {   
            e.printStackTrace();   
        }   
        
this.driver = props.getProperty("driver");   
        
this.url = props.getProperty("url");   
        
this.user = props.getProperty("user");   
        
this.password = props.getProperty("password");   
    }   
    
//implement the Connection   
    private void setConn(){   
        
try {   
            Class.forName(driver);   
            
this.conn = DriverManager.getConnection(url,user,password);   
        } 
catch(ClassNotFoundException classnotfoundexception) {   
              classnotfoundexception.printStackTrace();   
            System.err.println(
"db: " + classnotfoundexception.getMessage());   
        } 
catch(SQLException sqlexception) {   
            System.err.println(
"db.getconn(): " + sqlexception.getMessage());   
        }   
    }   
       
public void doInsert(String sql) {   
        
try {   
            Statement statement 
= conn.createStatement();   
            
int i = stm.executeUpdate(sql);   
        } 
catch(SQLException sqlexception) {   
            System.err.println(
"db.executeInset:" + sqlexception.getMessage());   
        }   
    }   
    
public void doDelete(String sql) {   
        
try {   
            stm 
= conn.createStatement();   
            
int i = stm.executeUpdate(sql);   
        } 
catch(SQLException sqlexception) {   
            System.err.println(
"db.executeDelete:" + sqlexception.getMessage());   
        }   
    }   
    
public void doUpdate(String sql) {   
        
try {   
            stm 
= conn.createStatement();   
            
int i = stm.executeUpdate(sql);   
        } 
catch(SQLException sqlexception) {   
            System.err.println(
"db.executeUpdate:" + sqlexception.getMessage());   
        }   
    }   
       
    
public ResultSet doSelect(String sql) {   
        
try {   
            stm 
= conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);   
            rs 
= stm.executeQuery(sql);   
        } 
catch(SQLException sqlexception) {   
            System.err.println(
"db.executeQuery: " + sqlexception.getMessage());   
        }   
        
return rs;   
    }   
    
public static void main(String[] args){   
        
try{   
            Db db 
= new Db();   
            Connection conn 
= db.getConn();   
            
if(conn != null && !conn.isClosed()) {   
                System.out.println(
"連結成功");   
                ResultSet rs 
= db.doSelect("select * from content");   
                
while(rs.next()){   
                    System.out.println(rs.getString(
1)+":"+rs.getString(2)+":"+rs.getString(3));   
                  }   
                rs.close();   
                conn.close();   
            }   
        }
catch(SQLException e) {   
            e.printStackTrace();   
        }   
    }     
}  

常用的java函数(四)中文转拼音
/**  
 * <p>  
 * Title:   
 * Description:中文转换为拼音  
 * 
@version 1.0  
 
*/  
public class ChineseSpelling {   
  
private static int[] pyvalue = new int[] { -20319-20317-20304-20295-20292-20283-20265-20257-20242-20230-20051-20036-20032-20026-20002-19990-19986-19982-19976-19805-19784-19775-19774-19763-19756-19751-19746-19741-19739-19728-19725-19715-19540-19531-19525-19515-19500-19484-19479-19467-19289-19288-19281-19275-19270-19263-19261-19249-19243-19242-19238-19235-19227-19224-19218-19212-19038-19023-19018-19006-19003-18996-18977-18961-18952-18783-18774-18773-18763-18756-18741-18735-18731-18722-18710-18697-18696-18526-18518-18501-18490-18478-18463-18448-18447-18446-18239-18237-18231-18220-18211-18201-18184-18183,   
            
-18181-18012-17997-17988-17970-17964-17961-17950-17947-17931-17928-17922-17759-17752-17733-17730-17721-17703-17701-17697-17692-17683-17676-17496-17487-17482-17468-17454-17433-17427-17417-17202-17185-16983-16970-16942-16915-16733-16708-16706-16689-16664-16657-16647-16474-16470-16465-16459-16452-16448-16433-16429-16427-16423-16419-16412-16407-16403-16401-16393-16220-16216-16212-16205-16202-16187-16180-16171-16169-16158-16155-15959-15958-15944-15933-15920-15915-15903-15889-15878-15707-15701-15681-15667-15661-15659-15652-15640-15631-15625-15454-15448-15436-15435-15419-15416-15408-15394,   
            
-15385-15377-15375-15369-15363-15362-15183-15180-15165-15158-15153-15150-15149-15144-15143-15141-15140-15139-15128-15121-15119-15117-15110-15109-14941-14937-14933-14930-14929-14928-14926-14922-14921-14914-14908-14902-14894-14889-14882-14873-14871-14857-14678-14674-14670-14668-14663-14654-14645-14630-14594-14429-14407-14399-14384-14379-14368-14355-14353-14345-14170-14159-14151-14149-14145-14140-14137-14135-14125-14123-14122-14112-14109-14099-14097-14094-14092-14090-14087-14083-13917-13914-13910-13907-13906-13905-13896-13894-13878-13870-13859-13847-13831-13658-13611-13601-13406-13404,   
            
-13400-13398-13395-13391-13387-13383-13367-13359-13356-13343-13340-13329-13326-13318-13147-13138-13120-13107-13096-13095-13091-13076-13068-13063-13060-12888-12875-12871-12860-12858-12852-12849-12838-12831-12829-12812-12802-12607-12597-12594-12585-12556-12359-12346-12320-12300-12120-12099-12089-12074-12067-12058-12039-11867-11861-11847-11831-11798-11781-11604-11589-11536-11358-11340-11339-11324-11303-11097-11077-11067-11055-11052-11045-11041-11038-11024-11020-11019-11018-11014-10838-10832-10815-10800-10790-10780-10764-10587-10544-10533-10519-10331-10329-10328-10322-10315-10309-10307,   
            
-10296-10281-10274-10270-10262-10260-10256-10254 };   
  
private static String[] pystr = new String[] { "a""ai""an""ang""ao""ba""bai""ban""bang""bao""bei""ben""beng""bi""bian""biao""bie""bin""bing""bo""bu""ca""cai""can""cang""cao""ce""ceng""cha""chai""chan""chang""chao""che""chen""cheng""chi""chong""chou""chu""chuai""chuan""chuang""chui""chun""chuo""ci""cong""cou""cu""cuan""cui""cun""cuo""da""dai""dan""dang""dao""de""deng""di""dian""diao""die""ding""diu""dong""dou""du""duan""dui""dun""duo""e""en""er""fa""fan""fang""fei""fen""feng""fo""fou""fu""ga""gai""gan""gang""gao""ge""gei""gen""geng""gong""gou""gu""gua""guai""guan""guang""gui""gun",   
"guo""ha""hai""han""hang""hao""he""hei""hen""heng""hong""hou""hu""hua""huai""huan""huang""hui""hun""huo""ji""jia""jian""jiang""jiao""jie""jin""jing""jiong""jiu""ju""juan""jue""jun""ka""kai""kan""kang""kao""ke""ken""keng""kong""kou""ku""kua""kuai""kuan""kuang""kui""kun""kuo""la""lai""lan""lang""lao""le""lei""leng""li""lia""lian""liang""liao""lie""lin""ling""liu""long""lou""lu""lv""luan""lue""lun""luo""ma""mai""man""mang""mao""me""mei""men""meng""mi""mian""miao""mie""min""ming""miu""mo""mou""mu""na""nai""nan""nang""nao""ne""nei""nen""neng""ni""nian""niang""niao",   
"nie""nin""ning""niu""nong""nu""nv""nuan""nue""nuo""o""ou""pa""pai""pan""pang""pao""pei""pen""peng""pi""pian""piao""pie""pin""ping""po""pu""qi""qia""qian""qiang""qiao""qie""qin""qing""qiong""qiu""qu""quan""que""qun""ran""rang""rao""re""ren""reng""ri""rong""rou""ru""ruan""rui""run""ruo""sa""sai""san""sang""sao""se""sen""seng""sha""shai""shan""shang""shao""she""shen""sheng""shi""shou""shu""shua""shuai""shuan""shuang""shui""shun""shuo""si""song""sou""su""suan""sui""sun""suo""ta""tai""tan""tang""tao""te""teng""ti""tian""tiao""tie""ting""tong""tou""tu""tuan""tui""tun",   
"tuo""wa""wai""wan""wang""wei""wen""weng""wo""wu""xi""xia""xian""xiang""xiao""xie""xin""xing""xiong""xiu""xu""xuan""xue""xun""ya""yan""yang""yao""ye""yi""yin""ying""yo""yong""you""yu""yuan""yue""yun""za""zai""zan""zang""zao""ze""zei""zen""zeng""zha""zhai""zhan""zhang""zhao""zhe""zhen""zheng""zhi""zhong""zhou""zhu""zhua""zhuai""zhuan""zhuang""zhui""zhun""zhuo""zi""zong""zou""zu""zuan""zui""zun""zuo" };   
  
private StringBuilder buffer;   
  
private String resource;   
  
private static ChineseSpelling chineseSpelling = new ChineseSpelling();   
  
public static ChineseSpelling getInstance() {   
return chineseSpelling;   
}   
  
public String getResource() {   
return resource;   
}   
  
public void setResource(String resource) {   
        
this.resource = resource;   
}   
  
private int getChsAscii(String chs) {   
int asc = 0;   
try {   
  
byte[] bytes = chs.getBytes("gb2312");   
  
if (bytes == null || bytes.length > 2 || bytes.length <= 0) { // 错误   
  
// log   
  
throw new RuntimeException("illegal resource string");   
// System.out.println("error");   
  
}   
if (bytes.length == 1) { // 英文字符   
  
                asc 
= bytes[0];   
}   
if (bytes.length == 2) { // 中文字符   
  
int hightByte = 256 + bytes[0];   
int lowByte = 256 + bytes[1];   
                asc 
= (256 * hightByte + lowByte) - 256 * 256;   
}   
catch (Exception e) {   
            System.out.println(
"ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);   
// e.printStackTrace();   
  
}   
return asc;   
}   
  
public String convert(String str) {   
        String result 
= null;   
int ascii = getChsAscii(str);   
// System.out.println(ascii);   
  
if (ascii > 0 && ascii < 160) {   
            result 
= String.valueOf((char) ascii);   
else {   
for (int i = (pyvalue.length - 1); i >= 0; i--) {   
if (pyvalue[i] <= ascii) {   
                    result 
= pystr[i];   
break;   
}   
}   
}   
return result;   
}   
  
public String getSelling(String chs) {   
        String key, value;   
        buffer 
= new StringBuilder();   
for (int i = 0; i < chs.length(); i++) {   
            key 
= chs.substring(i, i + 1);   
if (key.getBytes().length == 2) {   
                value 
= (String) convert(key);   
if (value == null) {   
                    value 
= "unknown";   
}   
else {   
                value 
= key;   
}   
  
            buffer.append(value);   
}   
return buffer.toString();   
}   
  
public String getSpelling() {   
return this.getSelling(this.getResource());   
}   
  
public static void main(String[] args) {   
// ChineseSpelling finder = new ChineseSpelling();   
  
  
        ChineseSpelling finder 
= ChineseSpelling.getInstance();   
        finder.setResource(
"中文字符");   
        System.out.println(finder.getSpelling());   
        System.out.println(finder.getSelling(
"英文字符Eng"));   
}   
  
}  

常用的java函数(五)人民币转成大写
/**  
    * 人民币转成大写  
    *   
    * 
@param value  
    * 
@return String  
    
*/  
   
public static String hangeToBig(double value)   
   {   
       
char[] hunit = { '''''' }; // 段内位置表示   
       char[] vunit = { '''亿' }; // 段名表示   
       char[] digit = { '''''''''''''''''''' }; // 数字表示   
       long midVal = (long) (value * 100); // 转化成整形   
       String valStr = String.valueOf(midVal); // 转化成字符串   
  
       String head 
= valStr.substring(0, valStr.length() - 2); // 取整数部分   
       String rail = valStr.substring(valStr.length() - 2); // 取小数部分   
  
       String prefix 
= ""// 整数部分转化的结果   
       String suffix = ""// 小数部分转化的结果   
       
// 处理小数点后面的数   
       if (rail.equals("00"))   
       { 
// 如果小数部分为0   
           suffix = "";   
       }   
       
else  
       {   
           suffix 
= digit[rail.charAt(0- '0'+ "" + digit[rail.charAt(1- '0'+ ""// 否则把角分转化出来   
       }   
       
// 处理小数点前面的数   
       char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组   
       char zero = '0'// 标志'0'表示出现过0   
       byte zeroSerNum = 0// 连续出现0的次数   
       for (int i = 0; i < chDig.length; i++)   
       { 
// 循环处理每个数字   
           int idx = (chDig.length - i - 1% 4// 取段内位置   
           int vidx = (chDig.length - i - 1/ 4// 取段位置   
           if (chDig[i] == '0')   
           { 
// 如果当前字符是0   
               zeroSerNum++// 连续0次数递增   
               if (zero == '0')   
               { 
// 标志   
                   zero = digit[0];   
               }   
               
else if (idx == 0 && vidx > 0 && zeroSerNum < 4)   
               {   
                   prefix 
+= vunit[vidx - 1];   
                   zero 
= '0';   
               }   
               
continue;   
           }   
           zeroSerNum 
= 0// 连续0次数清零   
           if (zero != '0')   
           { 
// 如果标志不为0,则加上,例如万,亿什么的   
               prefix += zero;   
               zero 
= '0';   
           }   
           prefix 
+= digit[chDig[i] - '0']; // 转化该数字表示   
           if (idx > 0)   
               prefix 
+= hunit[idx - 1];   
           
if (idx == 0 && vidx > 0)   
           {   
               prefix 
+= vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿   
           }   
       }   
  
       
if (prefix.length() > 0)   
           prefix 
+= ''// 如果整数部分存在,则有圆的字样   
       return prefix + suffix; // 返回正确表示  

常用的java函数(六)异常处理类
/**  
 * (#)ThrowableManager.java    1.0    Apr 10, 2008  
 *   
 * Copyright 2007- wargrey , Inc. All rights are reserved.  
 
*/  
package net.wargrey.application;   
  
import java.awt.Component;   
import javax.swing.JOptionPane;   
  
/**  
 * This class <code>ExceptionManager</code> and its subclasses are a form of   
 * <code>Exception</code>. It is used to wrap all the <code>Throwable</code> instances  
 * and handle them in a unified way. It will show the information which consists of   
 * StackTraces and Messages by using JOptionPanel.  
 *   
 * 
@author Estelle  
 * 
@version 1.0  
 * 
@see java.lang.Exception  
 * 
@since jdk 1.5  
 
*/  
public class ExceptionManager extends Exception {   
       
    
/**  
     * This field <code>alerter</code> is used to show the information the Class offered.  
     *   
     * 
@see javax.swing.JOptionPane  
     
*/  
    
private JOptionPane alerter;   
       
    
/**  
     * This static method create an instance of the ExceptionManager by invoking the   
     * constructor <code>ExceptionManager(String msg)</code>.  
     *   
     * 
@param msg    The message will pass the specified constructor  
     * 
@return    An instance of the ExceptionManager created by invoking the constructor  
     *             <code>ExceptionManager(String msg)</code>.  
     
*/  
    
public static ExceptionManager wrap(String msg){   
        
return new ExceptionManager(msg);   
    }   
       
    
/**  
     * This static method create an instance of the ExceptionManager by invoking the   
     * constructor <code>ExceptionManager(Throwable throwable)</code>.  
     *   
     * 
@param throwable        The cause will pass the specified constructor  
     * 
@return    An instance of the ExceptionManager created by invoking the constructor  
     *             <code>ExceptionManager(Throwable throwable)</code>.  
     
*/  
    
public static ExceptionManager wrap(Throwable throwable){   
        
return new ExceptionManager(throwable);   
    }   
       
    
/**  
     * This static method create an instance of the ExceptionManager by invoking the   
     * constructor <code>ExceptionManager(String msg,Throwable throwable)</code>.   
     *   
     * 
@param msg            The message will pass the specified constructor  
     * 
@param throwable        The cause will pass the specified constructor  
     * 
@return    An instance of the ExceptionManager created by invoking the constructor  
     *             <code>ExceptionManager(String msg, Throwable throwable)</code>  
     
*/  
    
public static ExceptionManager wrap(String msg,Throwable throwable){   
        
return new ExceptionManager(msg,throwable);   
    }   
       
    
/**  
     * Constructs a new instance with the specified detail message. The concrete handler   
     * is its super class. This constructor always used to construct a custom exception  
     * not wrapping the exist exception.  
     *   
     * 
@param msg        the detail message which is the part of the information will be  
     *                     shown.  
     
*/  
    
public ExceptionManager(String msg){   
        
super(msg);   
    }   
       
    
/**  
     * Constructs a new instance with the specified detail cause. The concrete handler   
     * is its super class. This constructor always used to wrap an exist exception.  
     *   
     * 
@param throwable        the cause which has been caught. It's detail message and   
     *                         stacktrace are the parts the information will be shown.  
     
*/  
    
public ExceptionManager(Throwable throwable){   
        
super(throwable);   
    }   
       
    
/**  
     * Constructs a new instance with the specified detail message and cause. The   
     * concrete handler is its super class. This constructor always used to construct  
     * an exception wrapping the exist exception but requires a custom message.   
     *   
     * 
@param msg        the detail message which is the part of the information will   
     *                     be shown.  
     * 
@param throwable    the cause which has been caught. It's stacktrace is the parts  
     *                     the information will be shown.  
     
*/  
    
public ExceptionManager(String msg,Throwable throwable){   
        
super(msg,throwable);   
    }   
       
    
/**  
     * Show the information with everything is default.  
     
*/  
    
public synchronized void alert(){   
        alert((Component)
null);   
    }   
       
    
/**  
     * Show the information in a dialog with the specified title   
     * "ThrowableManager Alerter". The dialog belongs to the given component which   
     * default is the screen.   
     *   
     * 
@param parent    The component cause the exception.  
     
*/  
    
public synchronized void alert(Component parent){   
        alert(parent,
"ThrowableManager Alerter");   
    }   
       
    
/**  
     * Show the information in a dialog with the specified title.  
     *   
     * 
@param title        The title of the dialog.  
     
*/  
    
public synchronized void alert(String title){   
        alert((Component)
null,title);   
    }   
       
    
/**  
     * Show the information in a dialog which has the specified title and belongs to the  
     * specified component.  
     *   
     * 
@param parent    The component cause the exception.  
     * 
@param title        The title of the dialog.  
     
*/  
    
public synchronized void alert(Component parent,String title){   
        StringBuilder errorMessage
=new StringBuilder();   
        errorMessage.append(
this.toString());   
        
for (StackTraceElement st:((this.getCause()==null)?this:this.getCause()).getStackTrace()){   
            errorMessage.append(
"\n\t     at ");   
            errorMessage.append(st.toString());   
        }           
        alerter.showMessageDialog(parent, errorMessage, title ,JOptionPane.ERROR_MESSAGE);   
    }   
}  

常用的java函数(七)各类数据库连接
MySQL:       
    String Driver
="com.mysql.jdbc.Driver";    //驱动程序   
    String URL="jdbc:mysql://localhost:3306/db_name";    //连接的URL,db_name为数据库名       
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).new Instance();   
    Connection con
=DriverManager.getConnection(URL,Username,Password);   
Microsoft SQL Server 
2.0驱动(3个jar的那个):   
    String Driver
="com.microsoft.jdbc.sqlserver.SQLServerDriver";    //连接SQL数据库的方法   
    String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";    //db_name为数据库名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).new Instance();    //加载数据可驱动   
    Connection con=DriverManager.getConnection(URL,UserName,Password);    //   
Microsoft SQL Server 3.0驱动(1个jar的那个): // 老紫竹完善   
    String Driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";    //连接SQL数据库的方法   
    String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";    //db_name为数据库名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).new Instance();    //加载数据可驱动   
    Connection con=DriverManager.getConnection(URL,UserName,Password);    //   
Sysbase:   
    String Driver
="com.sybase.jdbc.SybDriver";    //驱动程序   
    String URL="jdbc:Sysbase://localhost:5007/db_name";    //db_name为数据可名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();       
    Connection con
=DriverManager.getConnection(URL,Username,Password);   
Oracle(用thin模式):   
    String Driver
="oracle.jdbc.driver.OracleDriver";    //连接数据库的方法   
    String URL="jdbc:oracle:thin:@loaclhost:1521:orcl";    //orcl为数据库的SID   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();    //加载数据库驱动   
    Connection con=DriverManager.getConnection(URL,Username,Password);       
PostgreSQL:   
    String Driver
="org.postgresql.Driver";    //连接数据库的方法   
    String URL="jdbc:postgresql://localhost/db_name";    //db_name为数据可名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();       
    Connection con
=DriverManager.getConnection(URL,Username,Password);   
DB2:   
    String Driver
="com.ibm.db2.jdbc.app.DB2.Driver";    //连接具有DB2客户端的Provider实例   
    
//String Driver="com.ibm.db2.jdbc.net.DB2.Driver";    //连接不具有DB2客户端的Provider实例   
    String URL="jdbc:db2://localhost:5000/db_name";    //db_name为数据可名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();       
    Connection con
=DriverManager.getConnection(URL,Username,Password);   
Informix:   
    String Driver
="com.informix.jdbc.IfxDriver";       
    String URL
="jdbc:Informix-sqli://localhost:1533/db_name:INFORMIXSER=myserver";    //db_name为数据可名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();       
    Connection con
=DriverManager.getConnection(URL,Username,Password);   
JDBC
-ODBC:   
    String Driver
="sun.jdbc.odbc.JdbcOdbcDriver";   
    String URL
="jdbc:odbc:dbsource";    //dbsource为数据源名   
    String Username="username";    //用户名   
    String Password="password";    //密码   
    Class.forName(Driver).newInstance();       
    Connection con
=DriverManager.getConnection(URL,Username,Password); 

常用的java函数(八)TXT转XML
/*  
  *txt转换xml   
  
*/  
import java.io.BufferedReader;   
import java.io.BufferedWriter;   
import java.io.FileReader;   
import java.io.FileWriter;   
import java.util.StringTokenizer;   
  
public class TxtToXml {   
 
private String strTxtFileName;   
  
 
private String strXmlFileName;   
  
 
public TxtToXml() {   
  strTxtFileName 
= new String();   
  strXmlFileName 
= new String();   
 }   
  
 
public void createXml(String strTxt, String strXml) {   
  strTxtFileName 
= strTxt;   
  strXmlFileName 
= strXml;   
  String strTmp;   
  
try {   
   BufferedReader inTxt 
= new BufferedReader(new FileReader(   
     strTxtFileName));   
   BufferedWriter outXml 
= new BufferedWriter(new FileWriter(   
     strXmlFileName));   
   outXml.write(
"<?xml version= \"1.0\" encoding=\"gb2312\"?>");   
   outXml.newLine();   
   outXml.write(
"<people>");   
   
while ((strTmp = inTxt.readLine()) != null) {   
    StringTokenizer strToken 
= new StringTokenizer(strTmp, "");   
    String arrTmp[];   
    arrTmp 
= new String[3];   
    
for (int i = 0; i < 3; i++)   
     arrTmp[i] 
= new String("");   
    
int index = 0;   
    outXml.newLine();   
    outXml.write(
"    <students>");   
    
while (strToken.hasMoreElements()) {   
     strTmp 
= (String) strToken.nextElement();   
     strTmp 
= strTmp.trim();   
     arrTmp[index
++= strTmp;   
    }   
    outXml.newLine();   
    outXml.write(
"        <name>" + arrTmp[0+ "</name>");   
    outXml.newLine();   
    outXml.write(
"        <sex>" + arrTmp[1+ "</sex>");   
    outXml.newLine();   
    outXml.write(
"        <age>" + arrTmp[2+ "</age>");   
    outXml.newLine();   
    outXml.write(
"    </students>");   
   }   
   outXml.newLine();   
   outXml.write(
"</people>");   
   outXml.flush();   
  } 
catch (Exception e) {   
   e.printStackTrace();   
  }   
 }   
  
 
public static void main(String[] args) {   
  String txtName 
= "testtxt.txt";   
  String xmlName 
= "testxml.xml";   
  TxtToXml thisClass 
= new TxtToXml();   
  thisClass.createXml(txtName, xmlName);   
 }   
}  

常用的java函数(九)时间计算函数
import java.text.DecimalFormat;   
import java.util.Arrays;   
  
/**  
 * 时间计算工具类  
 
*/  
public class Time {   
  
    
/**  
     * 时间字段常量,表示“秒”  
      
*/  
    
public final static int SECOND = 0;   
       
    
/**  
     * 时间字段常量,表示“分”  
      
*/  
    
public final static int MINUTE = 1;   
       
    
/**  
     * 时间字段常量,表示“时”  
      
*/  
    
public final static int HOUR = 2;   
       
    
/**  
     * 时间字段常量,表示“天”  
      
*/  
    
public final static int DAY = 3;   
  
    
/**  
     * 各常量允许的最大值  
      
*/  
    
private final int[] maxFields = { 595923, Integer.MAX_VALUE - 1 };   
       
    
/**  
     * 各常量允许的最小值  
      
*/  
    
private final int[] minFields = { 000, Integer.MIN_VALUE };   
       
    
/**  
     * 默认的字符串格式时间分隔符  
      
*/  
    
private String timeSeparator = ":";   
       
    
/**  
     * 时间数据容器  
      
*/  
    
private int[] fields = new int[4];       
       
    
/**  
     * 无参构造,将各字段置为 0  
     
*/  
    
public Time() {   
        
this(0000);   
    }   
  
    
/**  
     * 使用时、分构造一个时间  
      * 
@param hour      小时  
      * 
@param minute    分钟  
      
*/  
    
public Time(int hour, int minute) {   
        
this(0, hour, minute, 0);   
    }   
  
    
/**  
     * 使用时、分、秒构造一个时间  
      * 
@param hour      小时  
      * 
@param minute    分钟  
      * 
@param second    秒  
      
*/  
    
public Time(int hour, int minute, int second) {   
        
this(0, hour, minute, second);   
    }   
       
    
/**  
     * 使用一个字符串构造时间<br/>  
     * Time time = new Time("14:22:23");  
     * 
@param time      字符串格式的时间,默认采用“:”作为分隔符  
      
*/  
    
public Time(String time) {           
        
this(time, null);   
    }   
  
    
/**  
     * 使用天、时、分、秒构造时间,进行全字符的构造  
      * 
@param day       天  
      * 
@param hour      时  
      * 
@param minute    分  
      * 
@param second    秒  
      
*/  
    
public Time(int day, int hour, int minute, int second) {   
        set(DAY, day);   
        set(HOUR, hour);   
        set(MINUTE, minute);   
        set(SECOND, second);   
    }     
       
    
/**  
     * 使用一个字符串构造时间,指定分隔符<br/>  
     * Time time = new Time("14-22-23", "-");  
     * 
@param time      字符串格式的时间  
      
*/  
    
public Time(String time, String timeSeparator) {   
        
if(timeSeparator != null) {   
            setTimeSeparator(timeSeparator);   
        }   
        String pattern 
= patternQuote(this.timeSeparator);   
        String matcher 
= new StringBuffer()   
                                .append(
"\\d+?").append(pattern)   
                                .append(
"\\d+?").append(pattern)   
                                .append(
"\\d+?")   
                                .toString();   
        
if(!time.matches(matcher)) {   
            
throw new IllegalArgumentException(time + ", time format error, HH"  
                    
+ this.timeSeparator + "mm" + this.timeSeparator + "ss");   
        }           
        String[] times 
= time.split(pattern);   
        set(DAY, 
0);   
        set(HOUR, Integer.parseInt(times[
0]));   
        set(MINUTE, Integer.parseInt(times[
1]));   
        set(SECOND, Integer.parseInt(times[
2]));   
    }   
       
    
/**  
     * 设置时间字段的值  
     * 
@param field     时间字段常量  
     * 
@param value     时间字段的值  
     
*/  
    
public void set(int field, int value) {           
        
if(value < minFields[field]) {   
            
throw new IllegalArgumentException(value +   
                    
", time value must be positive.");   
        }   
        fields[field] 
= value % (maxFields[field] + 1);   
        
// 进行进位计算   
         int carry = value / (maxFields[field] + 1);   
        
if(carry > 0) {   
            
int upFieldValue = get(field + 1);   
            set(field 
+ 1, upFieldValue + carry);   
        }   
    }   
  
    
/**  
     * 获得时间字段的值  
      * 
@param field     时间字段常量  
      * 
@return          该时间字段的值  
      
*/  
    
public int get(int field) {   
        
if(field < 0 || field > fields.length - 1) {   
            
throw new IllegalArgumentException(field + ", field value is error.");   
        }   
        
return fields[field];   
    }   
  
    
/**  
     * 将时间进行“加”运算,即加上一个时间  
      * 
@param time      需要加的时间  
      * 
@return          运算后的时间  
      
*/  
    
public Time addTime(Time time) {   
        Time result 
= new Time();   
        
int up = 0;     // 进位标志   
         for (int i = 0; i < fields.length; i++) {   
            
int sum = fields[i] + time.fields[i] + up;   
            up 
= sum / (maxFields[i] + 1);   
            result.fields[i] 
= sum % (maxFields[i] + 1);   
        }   
        
return result;   
    }   
  
    
/**  
     * 将时间进行“减”运算,即减去一个时间  
      * 
@param time      需要减的时间  
      * 
@return          运算后的时间  
      
*/  
    
public Time subtractTime(Time time) {   
        Time result 
= new Time();   
        
int down = 0;       // 退位标志   
         for (int i = 0, k = fields.length - 1; i < k; i++) {   
            
int difference = fields[i] + down;   
            
if (difference >= time.fields[i]) {   
                difference 
-= time.fields[i];   
                down 
= 0;   
            } 
else {   
                difference 
+= maxFields[i] + 1 - time.fields[i];   
                down 
= -1;   
            }   
            result.fields[i] 
= difference;   
        }   
        result.fields[DAY] 
= fields[DAY] - time.fields[DAY] + down;   
        
return result;   
    }   
       
    
/**  
     * 获得时间字段的分隔符  
      * 
@return  
     
*/  
    
public String getTimeSeparator() {   
        
return timeSeparator;   
    }   
  
    
/**  
     * 设置时间字段的分隔符(用于字符串格式的时间)  
      * 
@param timeSeparator     分隔符字符串  
      
*/  
    
public void setTimeSeparator(String timeSeparator) {   
        
this.timeSeparator = timeSeparator;   
    }   
  
    
/**  
     * 正则表达式引用处理方法,源自 JDK 
@link java.util.regex.Pattern#quote(String)  
     
*/  
    
private String patternQuote(String s) {   
        
int slashEIndex = s.indexOf("\\E");   
        
if (slashEIndex == -1)   
            
return "\\Q" + s + "\\E";   
  
        StringBuilder sb 
= new StringBuilder(s.length() * 2);   
        sb.append(
"\\Q");   
        slashEIndex 
= 0;   
        
int current = 0;   
        
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {   
            sb.append(s.substring(current, slashEIndex));   
            current 
= slashEIndex + 2;   
            sb.append(
"\\E\\\\E\\Q");   
        }   
        sb.append(s.substring(current, s.length()));   
        sb.append(
"\\E");   
        
return sb.toString();   
    }   
  
    
public String toString() {   
        DecimalFormat df 
= new DecimalFormat("00");   
        
return new StringBuffer().append(fields[DAY]).append("")   
                    .append(df.format(fields[HOUR])).append(timeSeparator)   
                    .append(df.format(fields[MINUTE])).append(timeSeparator)   
                    .append(df.format(fields[SECOND]))   
                    .toString();   
    }   
  
    
public int hashCode() {   
        
final int PRIME = 31;   
        
int result = 1;   
        result 
= PRIME * result + Arrays.hashCode(fields);   
        
return result;   
    }   
  
    
public boolean equals(Object obj) {   
        
if (this == obj)   
            
return true;   
        
if (obj == null)   
            
return false;   
        
if (getClass() != obj.getClass())   
            
return false;   
        
final Time other = (Time) obj;   
        
if (!Arrays.equals(fields, other.fields)) {   
            
return false;   
        }   
        
return true;   
    }   
}  

常用的java函数(十)随机函数
/**   
 * 
@author talent_marquis<��˺��>   
 * Email: talent_marquis@163.com   
 * Copyright (C) 2007 talent_marquis<��˺��>   
 * All rights reserved.   
 
*/   
package com.dextrys.trilogy.util;   
  
import java.util.Arrays;   
  
import org.eclipse.swt.graphics.RGB;   
  
public class RandomUtil   
{   
  
    
/**  
     * 
@param args  
     
*/  
    
public static void main( String[] args )   
    {   
        
//System.out.println( getRandomNormalString( 8 ) );   
        int[] test = getRandomIntWithoutReduplicate( 04039 );   
        Arrays.sort( test );   
        
forint i : test )   
        {   
            System.out.println( i );   
        }   
    }   
  
    
/**  
     * get a integer array filled with random integer without reduplicate [min, max)  
     * 
@param min    the minimum value  
     * 
@param max the maximum value  
     * 
@param size the capacity of the array  
     * 
@return a integer array filled with random integer without redupulicate  
     
*/  
    
public static int[] getRandomIntWithoutReduplicate( int min, int max, int size )   
    {   
        
int[] result = new int[size];   
           
        
int arraySize = max - min;   
        
int[] intArray = new int[arraySize];   
        
// init intArray   
        forint i = 0 ; i < intArray.length ; i++ )   
        {   
            intArray[i] 
= i + min;   
        }   
        
// get randome interger without reduplicate   
        forint i = 0 ; i < size ; i++ )   
        {   
            
int c = getRandomInt( min, max - i );   
            
int index = c - min;   
            swap( intArray, index, arraySize 
- 1 - i );   
            result[i] 
= intArray[ arraySize - 1 - i ];   
        }   
                   
        
return result;   
    }   
       
    
private static void swap( int[] array, int x, int y )   
    {   
        
int temp = array[x];   
        array[x] 
= array[y];   
        array[y] 
= temp;   
    }   
       
    
/**  
     * get a random Integer with the range [min, max)  
     * 
@param min the minimum value  
     * 
@param max the maximum value  
     * 
@return the random Integer value  
     
*/  
    
public static int getRandomInt( int min, int max )   
    {   
        
// include min, exclude max   
        int result = min + new Double( Math.random() * ( max - min ) ).intValue();   
  
        
return result;   
    }   
  
    
/**  
     * get a random double with the range [min, max)  
     * 
@param min the minimum value  
     * 
@param max the maximum value  
     * 
@return the random double value  
     
*/  
    
public static double getRandomDouble( double min, double max )   
    {   
        
// include min, exclude max   
        double result = min + ( Math.random() * ( max - min ) );   
        
return result;   
    }   
  
    
/**  
     *   
     * 
@return a random char with the range ASCII 33(!) to ASCII 126(~)  
     
*/  
    
public static char getRandomChar()   
    {   
        
// from ASCII code 33 to ASCII code 126   
        int firstChar = 33// "!"   
        int lastChar = 126// "~"   
        char result = ( char ) ( getRandomInt( firstChar, lastChar + 1 ) );   
        
return result;   
    }   
       
    
/**  
     *   
     * 
@return a random rgb color  
     
*/  
    
public static RGB getRandomRGB()   
    {   
        
int red = getRandomInt(0,256);   
        
int green = getRandomInt(0,256);   
        
int blue = getRandomInt(0,256);   
           
        
return new RGB( red, green, blue );   
    }   
       
    
/**  
     *   
     * 
@return a random char with the range [0-9],[a-z],[A-Z]  
     
*/  
    
public static char getRandomNormalChar()   
    {   
        
// include 0-9,a-z,A-Z   
        int number = getRandomInt( 062 );   
        
int zeroChar = 48;   
        
int nineChar = 57;   
        
int aChar = 97;   
        
int zChar = 122;   
        
int AChar = 65;   
        
int ZChar = 90;   
           
        
char result;   
           
        
if( number < 10 )   
        {   
            result 
=  ( char ) ( getRandomInt( zeroChar, nineChar + 1 ) );   
            
return result;   
  
        }   
        
else if( number >= 10 && number < 36 )   
        {   
            result 
= ( char ) ( getRandomInt( AChar, ZChar + 1 ) );   
            
return result;   
        }   
        
else if( number >= 36 && number < 62 )   
        {   
            result 
=  ( char ) ( getRandomInt( aChar, zChar + 1 ) );   
            
return result;   
        }   
        
else  
        {   
            
return 0;   
        }   
    }   
  
    
/**  
     *   
     * 
@param length the length of the String  
     * 
@return a String filled with random char  
     
*/  
    
public static String getRandomString( int length )   
    {   
        
// include ASCII code from 33 to 126   
        StringBuffer result = new StringBuffer();   
        
forint i = 0; i < length; i++ )   
        {   
            result.append( getRandomChar() );   
        }   
        
return result.toString();   
    }   
       
    
/**  
     *       
     * 
@param length the length of the String  
     * 
@return a String filled with normal random char  
     
*/  
    
public static String getRandomNormalString( int length )   
    {   
        
// include 0-9,a-z,A-Z   
        StringBuffer result = new StringBuffer();   
        
forint i = 0; i < length; i++)   
        {   
            result.append( getRandomNormalChar() );   
        }   
        
return result.toString();   
    }   
}  

常用的java函数(十一)文件拷贝代码
import java.io.*;    
import java.util.ArrayList;    
import java.util.List;    
public class FileCopy {    
private String message = "";    
public String getMessage() {    
  
return message;    
}    
public void setMessage(String message) {    
  
this.message = message;    
}    
/**   
  * 将源文件拷贝到目标文件   
  *   
  * 
@param src   
  *            写源文件地址,需文件名   
  * 
@param des   
  *            写目标文件地址,无需文件名   
  
*/    
public boolean copyFile(String src, String des) {    
  File srcFile 
= new File(src);    
  File desDir 
= new File(des);    
  File desFile 
= new File(des + "/" + srcFile.getName());    
  
// 判断源文件是否存在    
  if (!srcFile.exists()) {    
   
this.setMessage("源文件不存在!");    
   
return false;    
  } 
else if (!srcFile.isFile()) {    
   
this.setMessage("源文件格式错!");    
   
return false;    
  }    
  
// 判断源文件是否存在    
  if (!desDir.exists()) {    
   
this.setMessage("目标目录不存在!");    
   
return false;    
  } 
else if (!desDir.isDirectory()) {    
   
this.setMessage("不是有效的目录!");    
   
return false;    
  }    
  BufferedReader reader 
= null;    
  BufferedWriter writer 
= null;    
  String str;    
  
try {    
   reader 
= new BufferedReader(new FileReader(srcFile));    
   writer 
= new BufferedWriter(new FileWriter(desFile));    
   
// 判断目标文件是否存在及其格式,不存在就创建,格式不对先删除,存在就替代    
   if (!desFile.exists() || !desFile.isFile()) {    
    
if (desFile.exists()) {    
     desFile.delete();    
    }    
    desFile.createNewFile();    
   }    
   
// 从源文件读取数据,并写入目标文件    
   str = reader.readLine();    
   
while (str != null) {    
    writer.write(str);    
    writer.newLine();    
    str 
= reader.readLine();    
   }    
  } 
catch (IOException e) {    
   
this.setMessage(e.getMessage());    
   
return false;    
  } 
finally {    
   
if (reader != null) {    
    
try {    
     reader.close();    
    } 
catch (IOException e) {    
     
this.setMessage(e.getMessage());    
    }    
   }    
   
if (writer != null) {    
    
try {    
     writer.close();    
    } 
catch (IOException e) {    
     
this.setMessage(e.getMessage());    
    }    
   }    
  }    
  
return true;    
}    
private List fileList = new ArrayList();    
  
/**   
  * 列出所有文件   
  * 
@param srcFile   
  
*/    
private void file(File srcFile) {    
  
if (srcFile.isDirectory()) {    
   String[] files 
= srcFile.list();    
      
   
for (int i = 0; i < files.length; i++) {    
    File f 
= new File(srcFile + "/" + files[i]);    
    
// 如果是文件加入列表,否则递归列出    
    if (f.isFile()) {    
     fileList.add(f);    
    } 
else    
     file(f);    
   }    
  }
else this.setMessage(srcFile.getAbsolutePath()+"不是目录");    
}    
/**   
  * 建立目录   
  * 
@param des   
  * 
@throws IOException   
  
*/private void mkdir(File des) {    
  
if (!des.exists() || !des.isDirectory()) {    
   mkdir(des.getParentFile());    
   
if (des.exists()) {    
    des.delete();    
   }    
   des.mkdir();    
  }    
}    
/**   
  * 复制目录  将源目录下所有文件拷贝到目标目录下   
  * 
@param src  源目录   
   * 
@param des  目标目录   
  
*/    
public boolean copyDir(String src, String des) {    
  File srcFile 
= new File(src);    
  
if (!srcFile.exists()) {    
   
this.setMessage("源目录不存在!");    
   
return false;    
  } 
else if (!srcFile.isDirectory()) {    
   
this.setMessage(src+"不是有效的目录!");    
   
return false;    
  }    
  file(srcFile);    
      
  
for (int i = 0; i < fileList.size(); i++) {    
   String srcName 
= ((File) fileList.get(i)).getPath();    
   String desName 
= srcName.substring(src.length(), srcName.length());    
   desName 
= des + desName;    
   File dir
=new File(desName).getParentFile();    
   mkdir(dir);    
      
   
if(!copyFile(srcName, dir.getPath())){    
    
return false;    
   }    
  }    
  
return true;    
}    
public static void main(String[] args) {    
  
  FileCopy t 
= new FileCopy();    
  System.out.println(t.copyFile(
"D:/aaa.txt","E:"));    
  String src
="D:/asdf";    
  String des
="E:/adf";    
  System.out.println(t.copyDir(src, des));    
  System.out.println(t.getMessage());    
}    
  
}  

常用的java函数(十二)正则表达式用于字符串处理
正则表达式用于字符串处理、表单验证等场合,实用高效。现将一些常用的表达式收集于此,以备不时之需。    
  
匹配中文字符的正则表达式: [\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个英文字母或者下划线组成的字符串    
评注:最基本也是最常用的一些表达式   

常用的java函数(十三)日期公用处理类
import java.text.SimpleDateFormat;   
import java.util.ArrayList;   
import java.util.Calendar;   
import java.util.Date;   
import java.util.GregorianCalendar;   
import java.util.LinkedHashMap;   
  
/**  
 * 日期公用处理类  
 *   
 * 
@author SongJun  
 * 
@version 1.3  
 
*/  
public class DateUtil {   
    
/**  
     * 解析一个日期之间的所有月份  
     *   
     * 
@param beginDateStr  
     * 
@param endDateStr  
     * 
@return  
     
*/  
    
public static ArrayList getMonthList(String beginDateStr, String endDateStr) {   
        
// 指定要解析的时间格式   
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");   
        
// 返回的月份列表   
        String sRet = "";   
  
        
// 定义一些变量   
        Date beginDate = null;   
        Date endDate 
= null;   
  
        GregorianCalendar beginGC 
= null;   
        GregorianCalendar endGC 
= null;   
        ArrayList list 
= new ArrayList();   
  
        
try {   
            
// 将字符串parse成日期   
            beginDate = f.parse(beginDateStr);   
            endDate 
= f.parse(endDateStr);   
  
            
// 设置日历   
            beginGC = new GregorianCalendar();   
            beginGC.setTime(beginDate);   
  
            endGC 
= new GregorianCalendar();   
            endGC.setTime(endDate);   
  
            
// 直到两个时间相同   
            while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {   
                sRet 
= beginGC.get(Calendar.YEAR) + "-"  
                        
+ (beginGC.get(Calendar.MONTH) + 1);   
                list.add(sRet);   
                
// 以月为单位,增加时间   
                beginGC.add(Calendar.MONTH, 1);   
            }   
            
return list;   
        } 
catch (Exception e) {   
            e.printStackTrace();   
            
return null;   
        }   
    }   
  
    
/**  
     * 解析一个日期段之间的所有日期  
     *   
     * 
@param beginDateStr  
     *            开始日期  
     * 
@param endDateStr  
     *            结束日期  
     * 
@return  
     
*/  
    
public static ArrayList getDayList(String beginDateStr, String endDateStr) {   
        
// 指定要解析的时间格式   
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");   
  
        
// 定义一些变量   
        Date beginDate = null;   
        Date endDate 
= null;   
  
        Calendar beginGC 
= null;   
        Calendar endGC 
= null;   
        ArrayList list 
= new ArrayList();   
  
        
try {   
            
// 将字符串parse成日期   
            beginDate = f.parse(beginDateStr);   
            endDate 
= f.parse(endDateStr);   
  
            
// 设置日历   
            beginGC = Calendar.getInstance();   
            beginGC.setTime(beginDate);   
  
            endGC 
= Calendar.getInstance();   
            endGC.setTime(endDate);   
            SimpleDateFormat sdf 
= new SimpleDateFormat("yyyy-MM-dd");   
  
            
// 直到两个时间相同   
            while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {   
  
                list.add(sdf.format(beginGC.getTime()));   
                
// 以日为单位,增加时间   
                beginGC.add(Calendar.DAY_OF_MONTH, 1);   
            }   
            
return list;   
        } 
catch (Exception e) {   
            e.printStackTrace();   
            
return null;   
        }   
    }   
  
    
public static ArrayList getYearList() {   
        ArrayList list 
= new ArrayList();   
        Calendar c 
= null;   
        c 
= Calendar.getInstance();   
        c.setTime(
new Date());   
        
int currYear = Calendar.getInstance().get(Calendar.YEAR);   
  
        
int startYear = currYear - 5;   
        
int endYear = currYear + 10;   
        
for (int i = startYear; i < endYear; i++) {   
            list.add(
new Integer(i));   
        }   
        
return list;   
    }   
  
    
public static int getCurrYear() {   
        
return Calendar.getInstance().get(Calendar.YEAR);   
    }   
  
    
/**  
     * 得到某一年周的总数  
     *   
     * 
@param year  
     * 
@return  
     
*/  
    
public static LinkedHashMap getWeekList(int year) {   
        LinkedHashMap map 
= new LinkedHashMap();   
        Calendar c 
= new GregorianCalendar();   
        c.set(year, Calendar.DECEMBER, 
31235959);   
        
int count = getWeekOfYear(c.getTime());   
  
        SimpleDateFormat sdf 
= new SimpleDateFormat("yyyy-MM-dd");   
        String dayOfWeekStart 
= "";   
        String dayOfWeekEnd 
= "";   
        
for (int i = 1; i <= count; i++) {   
            dayOfWeekStart 
= sdf.format(getFirstDayOfWeek(year, i));   
            dayOfWeekEnd 
= sdf.format(getLastDayOfWeek(year, i));   
            map.put(
new Integer(i), ""+i+"周(从"+dayOfWeekStart + "" + dayOfWeekEnd+")");   
        }   
        
return map;   
  
    }   
       
    
/**  
     * 得到一年的总周数  
     * 
@param year  
     * 
@return  
     
*/  
    
public static int getWeekCountInYear(int year){   
        Calendar c 
= new GregorianCalendar();   
        c.set(year, Calendar.DECEMBER, 
31235959);   
        
int count = getWeekOfYear(c.getTime());   
        
return count;   
    }   
  
    
/**  
     * 取得当前日期是多少周  
     *   
     * 
@param date  
     * 
@return  
     
*/  
    
public static int getWeekOfYear(Date date) {   
        Calendar c 
= new GregorianCalendar();   
        c.setFirstDayOfWeek(Calendar.MONDAY);   
        c.setMinimalDaysInFirstWeek(
7);   
        c.setTime(date);   
  
        
return c.get(Calendar.WEEK_OF_YEAR);   
    }   
  
    
/**  
     * 得到某年某周的第一天  
     *   
     * 
@param year  
     * 
@param week  
     * 
@return  
     
*/  
    
public static Date getFirstDayOfWeek(int year, int week) {   
        Calendar c 
= new GregorianCalendar();   
        c.set(Calendar.YEAR, year);   
        c.set(Calendar.MONTH, Calendar.JANUARY);   
        c.set(Calendar.DATE, 
1);   
  
        Calendar cal 
= (GregorianCalendar) c.clone();   
        cal.add(Calendar.DATE, week 
* 7);   
  
        
return getFirstDayOfWeek(cal.getTime());   
    }   
  
    
/**  
     * 得到某年某周的最后一天  
     *   
     * 
@param year  
     * 
@param week  
     * 
@return  
     
*/  
    
public static Date getLastDayOfWeek(int year, int week) {   
        Calendar c 
= new GregorianCalendar();   
        c.set(Calendar.YEAR, year);   
        c.set(Calendar.MONTH, Calendar.JANUARY);   
        c.set(Calendar.DATE, 
1);   
  
        Calendar cal 
= (GregorianCalendar) c.clone();   
        cal.add(Calendar.DATE, week 
* 7);   
  
        
return getLastDayOfWeek(cal.getTime());   
    }   
       
    
/**  
     * 得到某年某月的第一天  
     * 
@param year  
     * 
@param month  
     * 
@return  
     
*/  
    
public static Date getFirestDayOfMonth(int year,int month){   
        month 
= month-1;   
        Calendar   c   
=   Calendar.getInstance();      
        c.set(Calendar.YEAR, year);   
        c.set(Calendar.MONTH, month);   
           
        
int day = c.getActualMinimum(c.DAY_OF_MONTH);   
  
        c.set(Calendar.DAY_OF_MONTH, day);   
        
return c.getTime();   
           
    }   
       
    
/**  
     * 提到某年某月的最后一天  
     * 
@param year  
     * 
@param month  
     * 
@return  
     
*/  
    
public static Date getLastDayOfMonth(int year,int month){   
        month 
= month-1;   
        Calendar   c   
=   Calendar.getInstance();      
        c.set(Calendar.YEAR, year);   
        c.set(Calendar.MONTH, month);   
        
int day = c.getActualMaximum(c.DAY_OF_MONTH);   
        c.set(Calendar.DAY_OF_MONTH, day);   
        
return c.getTime();   
    }   
  
    
/**  
     * 取得当前日期所在周的第一天  
     *   
     * 
@param date  
     * 
@return  
     
*/  
    
public static Date getFirstDayOfWeek(Date date) {   
        Calendar c 
= new GregorianCalendar();   
        c.setFirstDayOfWeek(Calendar.MONDAY);   
        c.setTime(date);   
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); 
// Monday   
        return c.getTime();   
    }   
  
    
/**  
     * 取得当前日期所在周的最后一天  
     *   
     * 
@param date  
     * 
@return  
     
*/  
    
public static Date getLastDayOfWeek(Date date) {   
        Calendar c 
= new GregorianCalendar();   
        c.setFirstDayOfWeek(Calendar.MONDAY);   
        c.setTime(date);   
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() 
+ 6); // Sunday   
        return c.getTime();   
    }   
  
}  
posted on 2008-11-26 09:41 芦苇 阅读(11846) 评论(4)  编辑  收藏 所属分类: JAVA其他

Feedback

# 帮帮忙 2008-12-19 08:41 ss
//利用Math类中random(),从a到z字母中,设法生成100个随机字符,并输出打印结果
//class RandomChar{
// 获得随机字符
// char[ ] getRandomChar(){… }
// 打印随即字符
//Void print( char a[ ]){…… }
//class Test{
//main(String args[] ){
// RandomChar rc=new RandomChar();
// add code …………….
// …..
//}  回复  更多评论
  

# re: 常用的java函数 2011-05-19 19:49 仿珍珠
很复杂,博主牛  回复  更多评论
  

# re: 常用的java函数 2014-08-10 12:30 一叶知秋
很实用,非常感谢,收藏了  回复  更多评论
  

# re: 常用的java函数 2014-11-25 19:46 regbo
很实用,谢谢楼主  回复  更多评论
  


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


网站导航: