java常用的读取配置文件方法

 1 package com.spenser.props;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileInputStream;
 5 import java.io.InputStream;
 6 import java.util.Properties;
 7 import java.util.ResourceBundle;
 8 
 9 public class LoadProps {
10     /**
11      * readPackage()方法加载包下的配置文件
12      */
13     public static void readPackage(){
14         try {  
15             // 可以加包名,例如org.config指的是org包下config.properties这个配置文件  
16             ResourceBundle resbun = ResourceBundle.getBundle("com.spenser.props.config");  
17             String str = resbun.getString("test");  
18             System.out.println("属性值:" + str);  
19         } catch (Exception e) {  
20             e.printStackTrace();  
21         }
22     }
23     
24     /**
25      * readSrc()方法加载src下的配置文件
26      */
27     public static void readSrc(){
28         try {  
29             Properties props = new Properties();  
30             // 配置文件在class下,即Src下  
31             props.load(LoadProps.class.getClassLoader().getResourceAsStream("config.properties"));  
32             String str = props.getProperty("test");  
33             System.out.println("属性值:" + str);  
34         } catch (Exception e) {  
35             e.printStackTrace();  
36         }  
37     }
38     
39     /**
40      * readWebInf()方法加载WEB-INF下的配置文件
41      */
42     public static void readWebInf(){
43         Properties props=new Properties();
44         try {
45             InputStream in=new BufferedInputStream(new FileInputStream("WebRoot/WEB-INF/config.properties"));
46             props.load(in);
47             String str=props.getProperty("test");
48             System.out.println("属性值: "+str);
49         } catch (Exception e) {
50             e.printStackTrace();
51         }
52     }
53     public static void main(String[] args) {
54         readPackage();
55         readSrc();
56         readWebInf();
57     }
58 }
原文地址:https://www.cnblogs.com/spenserliu/p/2983979.html