Java调用外部配置文件实例


如题,如何通过Java代码读取外部的配置文件来实现功能的修改。我们写一个Configure.properties文件放在某个目录下面,然后写入配置信息,也就是不同的包名。如下(这里配置的是用mysql数据库):

[shell]
bookDaoString=com.chinasofti.etc.dao.mysqlimpl.BookDaoImpl
userDaoString=com.chinasofti.etc.dao.mysqlimpl.UserDaoImpl
goodDaoString=com.chinasofti.etc.dao.mysqlimpl.GoodDaoImpl
[/shell]

接下来就要写如何用这个文件了,上代码,这个代码实例只引用了上面第一行的配置信息,并实现了两个output()方法的调用:

[java]
package com.chinasofti.etc.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import com.chinasofti.etc.dao.RBookDao;

public class TestR {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// RBookDao rBookDao = new com.chinasofti.etc.dao.seimpl.RBookDaoImpl();

File file = new File("F:\\Config.properties");
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
String daoString = properties.getProperty("bookDaoString");

RBookDao rBookDao = (RBookDao) Class.forName(daoString).newInstance();

rBookDao.outputOne();
rBookDao.outputTwo();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

[/java]

发表评论