首页 > 编程语言 > 详细

Java在Web项目中读取properties文件

时间:2014-09-15 19:28:39      阅读:286      评论:0      收藏:0      [点我收藏+]
 1 import java.io.FileNotFoundException;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.sql.SQLException;
 5 import java.util.Properties;
 6 
 7 import javax.sql.DataSource;
 8 
 9 import com.alibaba.druid.pool.DruidDataSourceFactory;
10 
11 public class JDBCUtils
12 {
13     protected static DataSource ds;
14 
15     static
16     {
17         try
18         {
19             Properties properties = loadPropertyFile("druid.properties");
20             ds = DruidDataSourceFactory.createDataSource(properties);
21         }
22         catch (Exception e)
23         {
24             e.printStackTrace();
25         }
26     }
27 
28     public static Properties loadPropertyFile(String fileName)
29     {
30         if (null == fileName || fileName.equals(""))
31         {
32             throw new IllegalArgumentException("Properties file path can not be null: " + fileName);
33         }
34 
35         InputStream inputStream = null;
36         Properties properties = null;
37         try
38         {
39             inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream(fileName);
40             properties = new Properties();
41             properties.load(inputStream);
42         }
43         catch (FileNotFoundException e)
44         {
45             throw new IllegalArgumentException("Properties file not found: " + fileName);
46         }
47         catch (IOException e)
48         {
49             throw new IllegalArgumentException("Properties file can not be loading: " + fileName);
50         }
51         finally
52         {
53             try
54             {
55                 if (inputStream != null)
56                 {
57                     inputStream.close();
58                 }
59             }
60             catch (IOException e)
61             {
62                 e.printStackTrace();
63             }
64         }
65         return properties;
66     }
67 
68     /**
69      * 获得数据源
70      * 
71      * @return
72      */
73     public static DataSource getDataSource()
74     {
75         return ds;
76     }
77 
78     public static void closeConnection() throws SQLException
79     {
80         if (ds != null && ds.getConnection() != null && !ds.getConnection().isClosed())
81         {
82             ds.getConnection().close();
83         }
84     }
85 }

 

Java在Web项目中读取properties文件

原文:http://www.cnblogs.com/sourceforge/p/java-properties.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!