读取配置文件
读取properties配置文件
properties类中的主要方法
1)getProperty(String key)
用指定的键在此属性列表中搜索属性。也就是通过参数key,得到key所对应的value。
2)load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。以供getProperty( String key)来搜索。
3)setProperty(String key, String value)
调用Hashtable的方法put 。他通过调用基类的put方法来设置键-值对。
4)store(OutputStream out, String comments)
以适合使用load方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流。与load方法相反,该方法将键-值对写入到指定的文件中去。
5)clear()
清除所有装载的键-值对。该方法在基类中提供
| 12
 
 | apple=src.main.java.per.hyc.ReflexAndInvokeTest.Appleorange=src.main.java.per.hyc.ReflexAndInvokeTest.Orange
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | import java.io.File;import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.util.Properties;
 
 
 
 
 public class GetProperties {
 public static Properties getPro(String pathname) {
 Properties pro = new Properties();
 File f = new File(pathname);
 try {
 if (f.exists()) {
 pro.load(new FileInputStream(f));
 }
 
 else {
 pro.setProperty("apple", "per.hyc.ReflexAndInvokeTest.Apple");
 pro.setProperty("orange", "per.hyc.ReflexAndInvokeTest.Orange");
 pro.store(new FileOutputStream(f), "FRUIT CLASS");
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 return pro;
 }
 }
 
 | 
读取xml配置文件
| 12
 3
 4
 5
 
 | <?xml version="1.0"?><config>
 <className>per.hyc.designPattern.Bridge.Blue</className>
 <className>per.hyc.designPattern.Bridge.SmallPen</className>
 </config>
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 
 | import javax.xml.parsers.*;import org.w3c.dom.*;
 import java.io.*;
 
 
 
 
 public class XMLUtilPen {
 
 public static Object getBean(String args) {
 try {
 
 DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = dFactory.newDocumentBuilder();
 Document doc;
 doc = builder.parse(new File(".\\src\\main\\resources\\configPen.xml"));
 Node classNode = null;
 NodeList nl = doc.getElementsByTagName("className");
 
 if (args.equals("color")) {
 
 classNode = nl.item(0).getFirstChild();
 } else if (args.equals("pen")) {
 
 classNode = nl.item(1).getFirstChild();
 }
 
 String cName = classNode.getNodeValue();
 
 return Class.forName(cName).newInstance();
 } catch (Exception e) {
 e.printStackTrace();
 return null;
 }
 }
 }
 
 | 
Spring 读取properties文件
Java中读取Properties配置文件的几种方式
- @ConfigurationProperties(prefix = “student”)
- @Value
- Environment
- 详见项目springbootdemo
利用第三方配置工具owner读取配置文件