JAVA读取配置文件的方法

目录

JAVA读取配置文件的方法

普通java项目

1、classLoader

//主要通过当前类的加载器加载classpath下的资源文件,局限是classpath下的 
//getResourceAsStream的路径相当于${classpath}/ 参数相对于这个路径来的
Properties properties = new Properties();
InputStream in = PaySupportUtils.class.getClassLoader()
                    .getResourceAsStream("pay.properties");
try {
    properties.load(in);
    String url = properties.getProperty("pay.url");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


//ClassLoader.getResource(), 参数为空是当前class的路径,'/'为classpath根路径
String path = PaySupportUtils.class.getResource("").getPath();
String path2 = PaySupportUtils.class.getResource("/").getPath();

2、通过InputStream进行读取文件

//可以读取任意路径的文件
Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = 
    new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bufferedReader);
properties.getProperty(String key);

3、使用ResourceBundle进行读取

//这种读取方式跟使用ClassLoader基本一致,路径也是classpath/ 
ResourceBundle bundle = ResourceBundle.getBundle("static/pay2");
bundle.getString("pay.userid")

4、使用Spring提供的PropertiesLoaderUtils.loadAllProperties

//跟ClassLoader、ResourceBundle 路径一致都是classpath/为根路径的
//还有一个好处是Spring进行了加强,可以对文件的内容改变进行实时体现,其他的方法不行
Properties ps = PropertiesLoaderUtils.loadAllProperties("pay.properties");
ps.getProperty("pay.money", "10000");

WEB项目

1、采用ServletContext读取放在src和WEB-INF中的配置文件

//跟其他的没有什么区别,不过这个是获取文件的实际路径,然后进行流读取,路径以 / 开头
String path = "/WEB-INF/classes/db1.properties";
InputStream in = this.getServletContext().getResourceAsStream(path);

2、使用与普通java项目一样的获取方式

猜你喜欢

转载自www.cnblogs.com/itck/p/10301876.html