JAVA常用函数1

    /**
     * 将某个日期以固定格式转化成字符串
     * 
     * 
@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(
"");
    }

    wait();    
//线程等待 
    notify();  //激活一个线程


/* * 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();
        }
    }  
}

DBConf.properties: 
driver
=oracle.jdbc.driver.OracleDriver 
url
=jdbc:oracle:thin:@tdt151:1521:train 
user
=XX 
password
=XX 


    
/**
     * 人民币转成大写
     * 
     * 
@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; // 返回正确表示
    }

    
public static String getURLByDBInfo(DBInfo dbInfo)
    {
        String url 
= "";
        
if(dbInfo.getDbType() != null)
            
if(dbInfo.getDbType().equals("SQLSERVER"))
                url 
= (new StringBuilder("jdbc:microsoft:sqlserver://")).append(dbInfo.getDbHost()).append(":").append(dbInfo.getDbPort()).append(";DatabaseName=").append(dbInfo.getDbSID()).toString();
            
else
            
if(dbInfo.getDbType().equals("ORACLE"))
                url 
= (new StringBuilder("jdbc:oracle:thin:@")).append(dbInfo.getDbHost()).append(":").append(dbInfo.getDbPort()).append(":").append(dbInfo.getDbSID()).toString();
            
else
            
if(dbInfo.getDbType().equals("ORACLE_DSP"))
                url 
= (new StringBuilder("jdbc:dsp@")).append(dbInfo.getDbHost()).append(":").append(dbInfo.getDbPort()).append("/").append(dbInfo.getDbSID()).append("/").append(dbInfo.getNamespace()).toString();
            
else
            
if(dbInfo.getDbType().equals("SYBASE"))
                url 
= "jdbc:sybase:Tds:";
            
else
                url 
= "sun.jdbc.odbc.JdbcOdbcDriver";
        
return url;
    }

    
/**
     * 全角字符转半角字符
     * 
     * 
@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);
    }

    
/**
     * 设置JSpinner的编辑属性
     * 
@param spinner 目标JSpinner
     * 
@param isAllowInvalid 是否允许输入非法值
     * 
@param isEditable 是否允许编辑
     
*/
    
public static void setAllowsInvalid(JSpinner spinner, boolean isAllowInvalid, boolean isEditable)
    {
        JSpinner.NumberEditor editor 
= new JSpinner.NumberEditor(spinner, "#");
        spinner.setEditor(editor);
        JFormattedTextField tf 
= ((JSpinner.NumberEditor)spinner.getEditor()).getTextField();
        tf.setEditable(isEditable);
        DefaultFormatterFactory factory 
= (DefaultFormatterFactory)tf.getFormatterFactory();
        NumberFormatter formatter 
= (NumberFormatter)factory.getDefaultFormatter();
        formatter.setAllowsInvalid(isAllowInvalid);
    }


    
/**   
     * 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
     * 
@param obj 原始对象
     * 
@return 新对象
     * 
@throws NoSuchMethodException    
     * 
@throws InvocationTargetException    
     * 
@throws IllegalAccessException    
     * 
@throws InstantiationException    
     * 
@throws SecurityException    
     * 
@throws IllegalArgumentException    
     
*/
    @SuppressWarnings(
"unchecked")
    
public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
                    InvocationTargetException, NoSuchMethodException
    {
        
//获得对象的类型    
        Class classType = obj.getClass();

        
//通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法    
        Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});

        
//获得对象的所有属性    
        Field[] fields = classType.getDeclaredFields();

        
for(int i = 0; i < fields.length; i++)
        {
            
//获取数组中对应的属性    
            Field field = fields[i];

            String fieldName 
= field.getName();
            String stringLetter 
= fieldName.substring(01).toUpperCase();

            
//获得相应属性的getXXX和setXXX方法名称    
            String getName = "get" + stringLetter + fieldName.substring(1);
            String setName 
= "set" + stringLetter + fieldName.substring(1);

            
//获取相应的方法    
            Method getMethod = classType.getMethod(getName, new Class[]{});
            Method setMethod 
= classType.getMethod(setName, new Class[]{field.getType()});

            
//调用源对象的getXXX()方法    
            Object value = getMethod.invoke(obj, new Object[]{});

            
//调用拷贝对象的setXXX()方法    
            setMethod.invoke(objectCopy, new Object[]{value});
        }

        
return objectCopy;
    }

//过滤特殊字符
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;
    }

//利用反射调用一个继承层次上的函数族,比如安装程序,有安装数据库的,安装文件系统的等,命名均已“install”开始,你就可以将参数part设为“install”,src是其实类实例,root是终止父类
    public static <T> void invokeMethods(String part,T src,Class root) throws ExceptionManager{
        
if (root!=null){
            
if (!root.isInstance(src))return;
            root
=(Class)root.getGenericSuperclass();
        }
        HashMap
<String,Method> invokees=new HashMap<String,Method>();
        Class target
=src.getClass();
        
do{
            Method [] methods
=target.getDeclaredMethods();
            
for (Method method:methods){
                String mn
=method.getName();
                Boolean isPass
=mn.startsWith(part);
                
if (isPass){
                    Integer nopt
=method.getParameterTypes().length;
                    Boolean isStatic
=Modifier.isStatic(method.getModifiers());
                    
if ((nopt==0)&&(!isStatic)){
                        
if (!invokees.containsKey(mn))
                            invokees.put(mn, method);
                    }
                }
            }
            target
=(Class)target.getGenericSuperclass();
        }
while(target!=root);
        Iterator
<String> methods=invokees.keySet().iterator();
        
while (methods.hasNext()){
            Method invokee
=invokees.get(methods.next());
            Boolean access
=invokee.isAccessible();
            invokee.setAccessible(
true);
            
try {
                invokee.invoke(src);
            } 
catch (InvocationTargetException e) {
                
throw ExceptionManager.wrap(e.getTargetException());
            }
catch (Exception e){}
            invokee.setAccessible(access);
        }
    }

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);




import java.text.DecimalFormat;

public class NumberUtil {
    
    
public static double decimalFormatD(int num, double d){
        String format 
= "0.";
        String result 
= "";
        
double db;
        
        
for(int i=0;i<num;i++)
            format 
= format.concat("0");
        
        DecimalFormat decimal 
= new DecimalFormat(format);
        result 
= decimal.format(d);
        db 
= Double.parseDouble(result);
        
        
return db;
    }
    
    
public static float decimalFormatF(int num, float f){
        String format 
= "0.";
        String result 
= "";
        
float fl;
        
        
for(int i=0;i<num;i++)
            format 
= format.concat("0");
        
        DecimalFormat decimal 
= new DecimalFormat(format);
        result 
= decimal.format(f);
        fl 
= Float.parseFloat(result);
        
        
return fl;
    }

    
    
public static String doubleToString(double f){       
        String s 
= "";
        
double a = 0;
        
        
while(f >= 1) {
            
            a 
= f%((double)10);
            
            s 
= String.valueOf((int)a) + s;
            f
=(f - a)/10;
        }
        
return s;
    }
}


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);
 }
}


 
/**
  * 写入日志
  * filePath 日志文件的路径
  * code 要写入日志文件的内容
  
*/
 
public static boolean print(String filePath,String code) {
  
try {
   File tofile
=new File(filePath);
   FileWriter fw
=new FileWriter(tofile,true);
   BufferedWriter bw
=new BufferedWriter(fw);
   PrintWriter pw
=new PrintWriter(bw);
   
   System.out.println(getDate()
+":"+code);
   pw.println(getDate()
+":"+code);
   pw.close();
   bw.close();
   fw.close();
   
return true;
  } 
catch (IOException e) {
   
return false;
  }
 }


 
/**
  * 判断是不是合法手机
  * handset 手机号码
  
*/
 
public static boolean isHandset(String handset) {
  
try {
   
if(!handset.substring(0,1).equals("1")) {
    
return false;
   }
   
if (handset==null || handset.length()!=11) {
    
return false;
   }
   String check 
= "^[0123456789]+$";
   Pattern regex 
= Pattern.compile(check);
   Matcher matcher 
= regex.matcher(handset);
   
boolean isMatched = matcher.matches();
   
if(isMatched) {
    
return true;
   } 
else {
    
return false;
   }
  } 
catch (RuntimeException e) {
   
return false;
  } 
 }
}


字符串匹配的算法. 
public String getMaxMatch(String a,String b) {   
        StringBuffer tmp 
= new StringBuffer();   
        String maxString 
= "";   
        
int max = 0;   
        
int len = 0;   
        
char[] aArray = a.toCharArray();   
        
char[] bArray = b.toCharArray();   
        
int posA = 0;   
        
int posB = 0;   
        
while(posA<aArray.length-max) {   
            posB 
= 0;   
            
while(posB<(bArray.length-max)) {                                   
                 
if(aArray[posA]==bArray[posB]) {   
                      len 
= 1;   
                      tmp 
= new StringBuffer();   
                      tmp.append(aArray[posA]);                                           
                      
while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len])) {   
                           tmp.append(aArray[posA
+len]);   
                           len
++;   
                      }   
                      
if(len>max) {   
                            max 
= len;   
                            maxString 
= tmp.toString();   
                      }   
                 }   
                      posB
++;   
            }   
                      posA
++;   
         }           
            
return maxString;                       
    }


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;
    }
}




posted @ 2009-10-09 22:56  angushine  阅读(449)  评论(0编辑  收藏  举报