为了降低代码的耦合性,很多时候,我们需要配置文件,比如数据库的连接,这样当数据库连接变化的时候,不用修改应用程序,也不用重新编译。在java中,提供了对property类型的文件的操作,可以很方便的读取属性值,比如下面的一个property文件:
####################################
# Database Connectivity Properties
####################################
driver=org.hsqldb.jdbcDriver
url=jdbc:hsqldb:mem:jpetstore
username=db2admin
password=password
用java代码读取也很方便,例如下面的代码片段:
Properties prop = new Properties();
InputStream fis = new FileInputStream("database.properties");
prop.load(fis);
String driver = prop.getProperty("driver");
在eclipse环境下,把database.properties放在工程目录下面就可以了。但是如果开发的是一个web应用,就会发现运行之后会出文件找不到的异常。目前有两个解决方法,就是一定要把这个属性文件放在classpath路径上,在web应用中需要把它放在classes目录下面,然后用ResourceBundle读取这个属性文件,具体如下:
static{
ResourceBundle resourceBundle = ResourceBundle.getBundle("database");
System.out.println(resourceBundle.getString("driver"));
}
或者: InputStream inStream = ClassName.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
try {
pro.load(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另外一种方法是把文件放在和调用类相同的目录下面,但是这个property文件会和类一起被打成jar包,调用代码如下:
Properties prop = new Properties();
InputStream fis = null;
String packageName = this.getClass().getPackage().getName();
String packageName = packageName .replaceAll("\\.", "/");
fis = this.getClass().getClassLoader().getResourceAsStream(packageName + "/database.properties");
prop.load(fis);
System.out.println("driver: " + prop.getProperty("driver"));
个人比较喜欢第一种方法
如果直接在jsp中操作,通过jsp内置对象可以获得可操作的绝对地址。
String path = pageContext.getServletContext().getRealPath("/");
String realPath = path+"/WEB-INF/classes/abc.properties";