常用java工具类(一)

1.读取配置文件

EnvironmentConfig.java

Java代码 复制代码 收藏代码
  1. package com.billows.util;
  2. import java.io.*;
  3. import java.util.*;
  4. /**
  5. * java 读取配置(属性)文件
  6. * @author Billows.Van
  7. * [email protected]
  8. */
  9. public class EnvironmentConfig {
  10. static EnvironmentConfig ec;// 创建对象ec
  11. private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前]
  12. private EnvironmentConfig() {
  13. super();
  14. }
  15. /**
  16. * 取得EnvironmentConfig的一个实例
  17. */
  18. public static EnvironmentConfig getInstance() {
  19. if (ec == null)
  20. ec = new EnvironmentConfig();// 创建EnvironmentConfig对象
  21. return ec;// 返回EnvironmentConfig对象
  22. }
  23. /**
  24. * 读取配置文件
  25. */
  26. public Properties getProperties(String fileName) {// 传递配置文件路径
  27. InputStream is = null;// 定义输入流is
  28. Properties p = null;
  29. try {
  30. p = (Properties) register.get(fileName);// 将fileName存于一个HashTable
  31. /**
  32. * 如果为空就尝试输入进文件
  33. */
  34. if (p == null) {
  35. try {
  36. is = new FileInputStream(fileName);// 创建输入流
  37. } catch (Exception e) {
  38. if (fileName.startsWith("/"))
  39. // 用getResourceAsStream()方法用于定位并打开外部文件。
  40. is = EnvironmentConfig.class.getResourceAsStream(fileName);
  41. else
  42. is = EnvironmentConfig.class.getResourceAsStream("/"+fileName);
  43. }
  44. p = new Properties();
  45. p.load(is);// 加载输入流
  46. register.put(fileName, p);// 将其存放于HashTable缓存
  47. is.close();// 关闭输入流
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace(System.out);
  51. }
  52. return p;// 返回Properties对象
  53. }
  54. /**
  55. * 此处插入方法描述。
  56. */
  57. public String getPropertyValue(String fileName, String strKey) {
  58. Properties p = getProperties(fileName);
  59. try {
  60. return (String) p.getProperty(strKey);
  61. } catch (Exception e) {
  62. e.printStackTrace(System.out);
  63. }
  64. return null;
  65. }
  66. }
package com.billows.util;

import java.io.*;
import java.util.*;

/**
 * java 读取配置(属性)文件  
 * @author Billows.Van 
 * [email protected]
 */
public class EnvironmentConfig {
	static EnvironmentConfig ec;// 创建对象ec
	private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前]

	private EnvironmentConfig() {
		super();
	}

	/**
	 * 取得EnvironmentConfig的一个实例
	 */
	public static EnvironmentConfig getInstance() {
		if (ec == null)
			ec = new EnvironmentConfig();// 创建EnvironmentConfig对象
		return ec;// 返回EnvironmentConfig对象
	}

	/**
	 * 读取配置文件
	 */
	public Properties getProperties(String fileName) {// 传递配置文件路径
		InputStream is = null;// 定义输入流is
		Properties p = null;
		try {
			p = (Properties) register.get(fileName);// 将fileName存于一个HashTable
			/**
			 * 如果为空就尝试输入进文件
			 */
			if (p == null) {
				try {
					is = new FileInputStream(fileName);// 创建输入流
				} catch (Exception e) {
					if (fileName.startsWith("/"))
						// 用getResourceAsStream()方法用于定位并打开外部文件。
						is = EnvironmentConfig.class.getResourceAsStream(fileName);
					else
						is = EnvironmentConfig.class.getResourceAsStream("/"+fileName);
				}
				p = new Properties();
				p.load(is);// 加载输入流
				register.put(fileName, p);// 将其存放于HashTable缓存
				is.close();// 关闭输入流
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return p;// 返回Properties对象
	}

	/**
	 * 此处插入方法描述。
	 */
	public String getPropertyValue(String fileName, String strKey) {
		Properties p = getProperties(fileName);
		try {
			return (String) p.getProperty(strKey);
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return null;
	}
}

 

用法:

Java代码 复制代码 收藏代码
  1. EnvironmentConfig ec=EnvironmentConfig.getInstance();
  2. String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");
EnvironmentConfig ec=EnvironmentConfig.getInstance();
String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");

2.Jdbc工具

JdbcUtil.java

Java代码 复制代码 收藏代码
  1. package com.billows.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. /**
  8. * @author Billows.Van [email protected]
  9. * @version 创建时间:2008-4-30 上午10:53:09 类说明
  10. */
  11. public class JdbcUtil {
  12. static {
  13. try {
  14. EnvironmentConfig ec=EnvironmentConfig.getInstance();
  15. String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");
  16. Class.forName(driverClassName);
  17. } catch (ClassNotFoundException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. public static Connection getConnection() throws SQLException {
  22. Connection conn = null;
  23. EnvironmentConfig ec=EnvironmentConfig.getInstance();
  24. String url=ec.getPropertyValue("/config/jdbc.properties", "jdbc.url");
  25. String name=ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
  26. String pwd=ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
  27. conn = DriverManager.getConnection(url, name, pwd);
  28. return conn;
  29. }
  30. public static void release(Connection conn, PreparedStatement ps,ResultSet rs) {
  31. if (rs != null)try {rs.close();} catch (SQLException e) {e.printStackTrace();}
  32. if (ps != null) try {ps.close();} catch (SQLException e) {e.printStackTrace();}
  33. if (conn!= null)try {conn.close();} catch (SQLException e) {e.printStackTrace();}
  34. }
  35. public static void release(Object obj) {
  36. if (obj instanceof Connection) {
  37. Connection conn = (Connection) obj;
  38. if (conn != null)
  39. try {
  40. conn.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. if (obj instanceof PreparedStatement) {
  46. PreparedStatement ps = (PreparedStatement) obj;
  47. if (ps != null)
  48. try {
  49. ps.close();
  50. } catch (SQLException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. if (obj instanceof ResultSet) {
  55. ResultSet rs = (ResultSet) obj;
  56. if (rs != null)
  57. try {
  58. rs.close();
  59. } catch (SQLException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }
  64. }
package com.billows.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Billows.Van [email protected]
 * @version 创建时间:2008-4-30 上午10:53:09 类说明
 */
public class JdbcUtil {
	static {
		try {
			EnvironmentConfig ec=EnvironmentConfig.getInstance();
			String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		Connection conn = null;
		EnvironmentConfig ec=EnvironmentConfig.getInstance();
		String url=ec.getPropertyValue("/config/jdbc.properties", "jdbc.url");
		String name=ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
		String pwd=ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
		conn = DriverManager.getConnection(url, name, pwd);
		return conn;
	}

	public static void release(Connection conn, PreparedStatement ps,ResultSet rs) {
		if (rs != null)try {rs.close();} catch (SQLException e) {e.printStackTrace();}
		if (ps != null) try {ps.close();} catch (SQLException e) {e.printStackTrace();}
		if (conn!= null)try {conn.close();} catch (SQLException e) {e.printStackTrace();}
	}

	public static void release(Object obj) {
		if (obj instanceof Connection) {
			Connection conn = (Connection) obj;
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		if (obj instanceof PreparedStatement) {
			PreparedStatement ps = (PreparedStatement) obj;
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		if (obj instanceof ResultSet) {
			ResultSet rs = (ResultSet) obj;
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}
}

 

3.java数据源

DBConnectionPool.java

Java代码 复制代码 收藏代码
  1. package com.billows.util;
  2. import java.sql.Connection;
  3. import javax.naming.Context;
  4. import javax.naming.InitialContext;
  5. import javax.sql.DataSource;
  6. public class DBConnectionPool {
  7. public static Connection getConnection() throws Exception{
  8. Context ctx = new InitialContext();
  9. DataSource ds = (DataSource)ctx.lookup("java:comp/env/hsql");
  10. // Context initContext = new InitialContext();
  11. // Context envContext = (Context)initContext.lookup("java:/comp/env");
  12. // DataSource ds = (DataSource)envContext.lookup("hsql");
  13. return ds.getConnection( );
  14. }
  15. }
package com.billows.util;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnectionPool {
	public static Connection getConnection() throws Exception{
		Context ctx = new InitialContext(); 
		DataSource ds = (DataSource)ctx.lookup("java:comp/env/hsql"); 
//		Context initContext = new InitialContext();
//		Context envContext = (Context)initContext.lookup("java:/comp/env");   
//		DataSource ds = (DataSource)envContext.lookup("hsql");
		return ds.getConnection( ); 
	}
}

4.hsqldb随web启动的Listener

Java代码 复制代码 收藏代码
  1. package com.billows.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import javax.servlet.ServletContextEvent;
  7. import javax.servlet.ServletContextListener;
  8. import org.apache.log4j.Logger;
  9. import org.hsqldb.Server;
  10. import com.billows.util.EnvironmentConfig;
  11. /**
  12. * 该listener随web服务启动 并同时启动hsql-server
  13. * @auth Billows.Van
  14. * [email protected]
  15. */
  16. public class HsqlListener implements ServletContextListener {
  17. public static final Logger log = Logger.getLogger("HsqlListener");
  18. private EnvironmentConfig ec=EnvironmentConfig.getInstance();
  19. /**配置文件中的占位符,代表webapp发布后的根目录.*/
  20. public static final String TOKEN = "${webapp.root}";
  21. /** 等待数据库停止的最大时间.*/
  22. public static final int WAIT_TIME = 1000;
  23. /**jdbc的url.*/
  24. private String url;
  25. /**登陆用户名.*/
  26. private String username;
  27. /**登陆密码.*/
  28. private String password;
  29. /**处理context初始化事件.
  30. * @param sce ServletContextEvent
  31. */
  32. public void contextInitialized(ServletContextEvent sce) {
  33. try {
  34. username = ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
  35. password = ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
  36. String databaseName = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbname");
  37. int port = Integer.parseInt(ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbport"));
  38. String hsqlPath = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbpath");
  39. // FIXME: 因为要用到getRealPath方法获得路径,在使用war包发布的时候会出现问题
  40. if (hsqlPath.startsWith(TOKEN)) {
  41. String webappRoot = sce.getServletContext().getRealPath("/").replace("\\", "/");
  42. hsqlPath = hsqlPath.substring(TOKEN.length());
  43. hsqlPath = webappRoot + hsqlPath;
  44. }
  45. String databasePath = hsqlPath + "/" + databaseName;
  46. url = "jdbc:hsqldb:hsql://localhost:" + port + "/" + databaseName;
  47. Server server = new Server();
  48. server.setDatabaseName(0, databaseName);
  49. server.setDatabasePath(0, databasePath);
  50. server.setPort(port);
  51. server.setSilent(true);
  52. server.start();
  53. Thread.sleep(WAIT_TIME);
  54. log.info("Hsqldb启动成功!");
  55. } catch (Exception ex) {
  56. log.error("Hsqldb启动失败:" + ex);
  57. }
  58. }
  59. /**
  60. * 处理context销毁事件.
  61. * @param sce ServletContextEvent
  62. */
  63. public void contextDestroyed(ServletContextEvent sce) {
  64. try {
  65. Class.forName("org.hsqldb.jdbcDriver");
  66. Connection conn = null;
  67. Statement state = null;
  68. try {
  69. // 向数据库发送shutdown命令,关闭数据库
  70. conn = DriverManager.getConnection(url, username, password);
  71. state = conn.createStatement();
  72. state.executeUpdate("SHUTDOWN;");
  73. try {
  74. Thread.sleep(WAIT_TIME);
  75. } catch (InterruptedException e) {
  76. e.printStackTrace();
  77. }
  78. log.info("关闭hsqldb数据库成功!");
  79. } catch (SQLException ex1) {
  80. log.error("关闭hsqldb数据库时出现异常:" + ex1);
  81. } finally {
  82. // 确保关闭Statement
  83. if (state != null) {
  84. try {
  85. state.close();
  86. state = null;
  87. } catch (SQLException ex1) {
  88. log.error("关闭Statement时异常:"+ex1);
  89. }
  90. }
  91. // 确保关闭Connection
  92. if (conn != null) {
  93. try {
  94. conn.close();
  95. conn = null;
  96. } catch (SQLException ex1) {
  97. log.error("关闭Connection时异常:"+ex1);
  98. }
  99. }
  100. }
  101. } catch (ClassNotFoundException ex) {
  102. log.error("HsqldbListener : contextDestoryed : error : " + ex);
  103. }
  104. }
  105. }
package com.billows.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.hsqldb.Server;

import com.billows.util.EnvironmentConfig;
/**
 * 该listener随web服务启动 并同时启动hsql-server
 * @auth Billows.Van 
 * [email protected]
 */
public class HsqlListener implements ServletContextListener {
	public static final Logger log = Logger.getLogger("HsqlListener");
	private EnvironmentConfig ec=EnvironmentConfig.getInstance();
	/**配置文件中的占位符,代表webapp发布后的根目录.*/
	public static final String TOKEN = "${webapp.root}";
	/** 等待数据库停止的最大时间.*/
	public static final int WAIT_TIME = 1000;
	/**jdbc的url.*/
	private String url;
	/**登陆用户名.*/
	private String username;
	/**登陆密码.*/
	private String password;
     /**处理context初始化事件. 
      * @param sce ServletContextEvent
      */  
     public void contextInitialized(ServletContextEvent sce) {  
         try {  
             username = ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
             password = ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
             String databaseName = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbname");
             int port = Integer.parseInt(ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbport"));  
             String hsqlPath = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbpath");
   
             // FIXME: 因为要用到getRealPath方法获得路径,在使用war包发布的时候会出现问题  
             if (hsqlPath.startsWith(TOKEN)) {  
                 String webappRoot = sce.getServletContext().getRealPath("/").replace("\\", "/");  
                 hsqlPath = hsqlPath.substring(TOKEN.length());  
                 hsqlPath = webappRoot + hsqlPath;
             }
             String databasePath = hsqlPath + "/" + databaseName;  
             url = "jdbc:hsqldb:hsql://localhost:" + port + "/" + databaseName;  
             Server server = new Server();  
             server.setDatabaseName(0, databaseName);
             server.setDatabasePath(0, databasePath);  
             server.setPort(port);  
             server.setSilent(true);
             server.start();
             Thread.sleep(WAIT_TIME);  
             log.info("Hsqldb启动成功!");
         } catch (Exception ex) {  
        	 log.error("Hsqldb启动失败:" + ex);  
         }  
     }  
   
     /** 
      * 处理context销毁事件. 
      * @param sce ServletContextEvent 
      */  
     public void contextDestroyed(ServletContextEvent sce) {  
         try {  
             Class.forName("org.hsqldb.jdbcDriver");  
             Connection conn = null;  
             Statement state = null;  
             try {
                 // 向数据库发送shutdown命令,关闭数据库  
                 conn = DriverManager.getConnection(url, username, password);  
                 state = conn.createStatement();  
                 state.executeUpdate("SHUTDOWN;");
                 try {
					Thread.sleep(WAIT_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				log.info("关闭hsqldb数据库成功!");
             } catch (SQLException ex1) {  
                 log.error("关闭hsqldb数据库时出现异常:" + ex1);  
             } finally {  
                 // 确保关闭Statement  
                 if (state != null) {  
                     try {  
                         state.close();  
                         state = null;  
                     } catch (SQLException ex1) {  
                    	 log.error("关闭Statement时异常:"+ex1);  
                     }  
                 }  
                 // 确保关闭Connection  
                 if (conn != null) {  
                     try {  
                         conn.close();  
                         conn = null;  
                     } catch (SQLException ex1) {  
                         log.error("关闭Connection时异常:"+ex1);  
                     }  
                 }  
             }  
         } catch (ClassNotFoundException ex) {  
             log.error("HsqldbListener : contextDestoryed : error : " + ex);  
         }  
     }  
}

其中, jdbc.properties内容为

Properties代码 复制代码 收藏代码
  1. jdbc.driverClassName=org.hsqldb.jdbcDriver
  2. jdbc.url=jdbc:hsqldb:hsql://localhost:9990/billows
  3. jdbc.dbname=billows
  4. jdbc.dbport=9990
  5. jdbc.dbpath=${webapp.root}/hsqldb
  6. jdbc.username=sa
  7. jdbc.password=
  8. jdbc.max_connections=30
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://localhost:9990/billows
jdbc.dbname=billows
jdbc.dbport=9990
jdbc.dbpath=${webapp.root}/hsqldb
jdbc.username=sa
jdbc.password=
jdbc.max_connections=30

在web.xml中添加以下代码即可

Xml代码 复制代码 收藏代码
  1. <listener>
  2. <listener-class>com.billows.util.HsqlListener</listener-class>
  3. </listener>
<listener>
	<listener-class>com.billows.util.HsqlListener</listener-class>
</listener>

 

你可能感兴趣的:(java)