我爱学Java之读取Properties的几种方法

来源:互联网 发布:office2011 for mac 编辑:程序博客网 时间:2024/06/05 10:59

首先贴出目录结构:

这里写图片描述

db.properties

这里写图片描述

1.Properties类的load()方法:

public static void main(String[] args) throws IOException{        InputStream in  = new BufferedInputStream(new FileInputStream("src/db.properties"));//相对于根路径        Properties p = new Properties();        p.load(in);        System.out.println(p.getProperty("user"));    }

2.使用class变量的getResourceAsStream()方法

public static void main(String[] args) throws IOException{        InputStream in  = Properties.class.getResourceAsStream("/db.properties");//不以"/"开头则默认为此类所在包下的资源,以’/'开头则是从ClassPath根下获取,ClassPath可以通过System.getProperty("java.class.path")获取。         Properties p = new Properties();        p.load(in);        System.out.println(p.getProperty("user"));    }

3.使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法

public static void main(String[] args) throws IOException{        InputStream in = ClassLoader.getSystemResourceAsStream("db.properties");//从classpath路径下        Properties p = new Properties();        p.load(in);        System.out.println(p.getProperty("user"));    }

4.使用class.getClassLoader().getResourceAsStream()方法

public static void main(String[] args) throws IOException{        InputStream in = Test.class.getClassLoader().getResourceAsStream("db.properties");//从classpath路径下,Test为运行该代码的类        Properties p = new Properties();        p.load(in);        System.out.println(p.getProperty("user"));    }

5.使用java.util.ResourceBundle类的getBundle()方法

public static void main(String[] args) throws IOException{        ResourceBundle rb = ResourceBundle.getBundle("db");             System.out.println(rb.getString("user"));    }

6.使用java.util.PropertyResourceBundle类的构造函数

public static void main(String[] args) throws IOException{         InputStream in = new BufferedInputStream(new FileInputStream("src/db.properties"));         ResourceBundle rb = new PropertyResourceBundle(in);         System.out.println(rb.getString("user"));    }

运行结果都为:

这里写图片描述

0 0
原创粉丝点击