Propertiesresources配置读取


读取Properties文件属性值

读取源路径配置文件

  1. InputStream in=null;
  2. //方式一:
  3. //in=new BufferedInputStream(new FileInputStream(new File("/application.properties")));
  4. //方式三:
  5. //in=this.getClass().getClassLoader().getResourceAsStream("/application.properties");
  6. //方式二:
  7. in=this.getClass().getResourceAsStream("/application.properties");
  8. Properties properties=new Properties();
  9. properties.load(in);
  10. String activeState = properties.getProperty("spring.profiles.active");

写入Properties文件属性值

  1. //1.先实例化一个Properties对象
  2. Properties properties = new Properties();
  3. try {
  4. //2.创建一个输出流对象,选择正确的目标文件路径(注意:该配置文件放在src目录下)
  5. FileOutputStream fos = new FileOutputStream("src/test2.properties",true);//这里true表示追加,如果不设为true的话,会将原文件清空后,重新添加,切记!!!
  6. OutputStreamWriter opw = new OutputStreamWriter(fos,"utf-8");//引入Writer,可以明确该输出流的字符集,确保写入配置文件的中文编码正确
  7. //3.将需要写入的属性内容通过set方法,存入properties对象中
  8. properties.setProperty("testSong","Someone Like You");
  9. properties.setProperty("testQQ","只能说我认了,也许是你怕了");
  10. //4.调用properties的存储方法
  11. properties.store(opw,"测试用数据");
  12. //5.关闭资源
  13. fos.close();
  14. } catch (FileNotFoundException e) {
  15. e.printStackTrace();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }

遍历Properties文件属性值

常用方式:

  1. //常用:属性遍历
  2. InputStream in=null;
  3. in=this.getClass().getResourceAsStream("/application.properties");
  4. Properties properties=new Properties();
  5. properties.load(in);
  6. for (String key : properties.stringPropertyNames()) {
  7. System.out.println(key + "=" + properties.getProperty(key));
  8. }

扩展:

  1. /**
  2. * 输出properties的key和value
  3. */
  4. public static void printProp(Properties properties) {
  5. System.out.println("---------(方式一)------------");
  6. for (String key : properties.stringPropertyNames()) {
  7. System.out.println(key + "=" + properties.getProperty(key));
  8. }
  9. System.out.println("---------(方式二)------------");
  10. Set<Object> keys = properties.keySet();//返回属性key的集合
  11. for (Object key : keys) {
  12. System.out.println(key.toString() + "=" + properties.get(key));
  13. }
  14. System.out.println("---------(方式三)------------");
  15. Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
  16. //返回的属性键值对实体
  17. for (Map.Entry<Object, Object> entry : entrySet) {
  18. System.out.println(entry.getKey() + "=" + entry.getValue());
  19. }
  20. System.out.println("---------(方式四)------------");
  21. Enumeration<?> e = properties.propertyNames();
  22. while (e.hasMoreElements()) {
  23. String key = (String) e.nextElement();
  24. String value = properties.getProperty(key);
  25. System.out.println(key + "=" + value);
  26. }
  27. }

资料学习与引用