By
Moment Only
更新日期:
Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易。
读取方式
1、基于ClassLoder读取配置文件
注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。
2、基于 InputStream 读取配置文件
注意:该方式的优点在于可以读取任意路径下的配置文件
代码实现
db.properties
1 2 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
| package jdbc.com.szxy.properties;
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties;
public class ProPertiesTest { public static void main(String[] args) throws Exception {
Properties pro1 = new Properties(); InputStream is1 = ProPertiesTest.class.getClassLoader().getResourceAsStream("db.properties"); pro1.load(is1); System.out.println(pro1.getProperty("user")); System.out.println(pro1.getProperty("pwd"));
Properties pro2 = new Properties(); InputStream is2 = new FileInputStream(new File("src/db.properties")); pro2.load(is2); System.out.println(pro2.getProperty("user")); System.out.println(pro2.getProperty("pwd")); } }
|