1、从项目中读取properties配置文件,新建一个main程序,对应位置建立一个名称为config.properties配置文件,随意放置一些键值对。IDEA建立配置文件,对应package鼠标右键,点击New,再点击Resource Bundle,弹出对话框输入名称保存即可。
以下实例,读取配置文件,然后遍历key值和value值,采用此种方式读取项目中配置文件,将不依赖具体环境。
1 public class HelloWorld { 2 public static void main(String[] args) { 3 Properties properties=new Properties(); 4 InputStream in=HelloWorld.class.getClassLoader().getResourceAsStream("Config/config.properties"); 5 try{ 6 properties.load(in); 7 Enumeration enumeration=properties.propertyNames(); 8 while (enumeration.hasMoreElements()){ 9 String strKey=(String)enumeration.nextElement(); 10 String strValue=properties.getProperty(strKey); 11 System.out.println("key:"+strKey); 12 System.out.println("Value:"+strValue); 13 } 14 }catch(IOException e){ 15 System.out.println("There is An IO error!"); 16 } 17 } 18 }
2、一些其它读取配置文件的方法