Propertiesresources配置读取
读取Properties文件属性值
读取源路径配置文件
InputStream in=null;//方式一://in=new BufferedInputStream(new FileInputStream(new File("/application.properties")));//方式三://in=this.getClass().getClassLoader().getResourceAsStream("/application.properties");//方式二:in=this.getClass().getResourceAsStream("/application.properties");Properties properties=new Properties();properties.load(in);String activeState = properties.getProperty("spring.profiles.active");
写入Properties文件属性值
//1.先实例化一个Properties对象Properties properties = new Properties();try {//2.创建一个输出流对象,选择正确的目标文件路径(注意:该配置文件放在src目录下)FileOutputStream fos = new FileOutputStream("src/test2.properties",true);//这里true表示追加,如果不设为true的话,会将原文件清空后,重新添加,切记!!!OutputStreamWriter opw = new OutputStreamWriter(fos,"utf-8");//引入Writer,可以明确该输出流的字符集,确保写入配置文件的中文编码正确//3.将需要写入的属性内容通过set方法,存入properties对象中properties.setProperty("testSong","Someone Like You");properties.setProperty("testQQ","只能说我认了,也许是你怕了");//4.调用properties的存储方法properties.store(opw,"测试用数据");//5.关闭资源fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
遍历Properties文件属性值
常用方式:
//常用:属性遍历InputStream in=null;in=this.getClass().getResourceAsStream("/application.properties");Properties properties=new Properties();properties.load(in);for (String key : properties.stringPropertyNames()) {System.out.println(key + "=" + properties.getProperty(key));}
扩展:
/*** 输出properties的key和value*/public static void printProp(Properties properties) {System.out.println("---------(方式一)------------");for (String key : properties.stringPropertyNames()) {System.out.println(key + "=" + properties.getProperty(key));}System.out.println("---------(方式二)------------");Set<Object> keys = properties.keySet();//返回属性key的集合for (Object key : keys) {System.out.println(key.toString() + "=" + properties.get(key));}System.out.println("---------(方式三)------------");Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();//返回的属性键值对实体for (Map.Entry<Object, Object> entry : entrySet) {System.out.println(entry.getKey() + "=" + entry.getValue());}System.out.println("---------(方式四)------------");Enumeration<?> e = properties.propertyNames();while (e.hasMoreElements()) {String key = (String) e.nextElement();String value = properties.getProperty(key);System.out.println(key + "=" + value);}}
资料学习与引用
