Java在Web项目中读取properties文件

时间:2023-03-09 09:07:36
Java在Web项目中读取properties文件
 import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; public class JDBCUtils
{
protected static DataSource ds; static
{
try
{
Properties properties = loadPropertyFile("druid.properties");
ds = DruidDataSourceFactory.createDataSource(properties);
}
catch (Exception e)
{
e.printStackTrace();
}
} public static Properties loadPropertyFile(String fileName)
{
if (null == fileName || fileName.equals(""))
{
throw new IllegalArgumentException("Properties file path can not be null: " + fileName);
} InputStream inputStream = null;
Properties properties = null;
try
{
inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream(fileName);
properties = new Properties();
properties.load(inputStream);
}
catch (FileNotFoundException e)
{
throw new IllegalArgumentException("Properties file not found: " + fileName);
}
catch (IOException e)
{
throw new IllegalArgumentException("Properties file can not be loading: " + fileName);
}
finally
{
try
{
if (inputStream != null)
{
inputStream.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
return properties;
} /**
* 获得数据源
*
* @return
*/
public static DataSource getDataSource()
{
return ds;
} public static void closeConnection() throws SQLException
{
if (ds != null && ds.getConnection() != null && !ds.getConnection().isClosed())
{
ds.getConnection().close();
}
}
}