1、首先给出我的properties文件,仅作测试用:config.properties
- name=huangyz
- password=huangyz@neusoft.com
2、给出工程目录结构。
3、下面给出两种方法:
一、采用绝对路径方法,给出源码。
- package parse;
- import java.util.*;
- import java.io.*;
- public class ParseProperties {
- public static void main(String args[]) {
- // 生成文件对象
- File pf = new File(System.getProperty("user.dir")
- + "/src/config/config.properties");
- // 生成文件输入流
- FileInputStream inpf = null;
- try {
- inpf = new FileInputStream(pf);
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 生成properties对象
- Properties p = new Properties();
- try {
- p.load(inpf);
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 输出properties文件的内容
- System.out.println("name:" + p.getProperty("name"));
- System.out.println("password:" + p.getProperty("password"));
- }
- }
二、采用相对定位方法,给出源码。
- package parse;
- import java.util.*;
- import java.io.*;
- public class ParseProperties {
- public static void main(String args[]) {
- // 生成输入流
- InputStream ins=ParseProperties.class.getResourceAsStream("../config/config.properties");
- // 生成properties对象
- Properties p = new Properties();
- try {
- p.load(ins);
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 输出properties文件的内容
- System.out.println("name:" + p.getProperty("name"));
- System.out.println("password:" + p.getProperty("password"));
- }
- }
看蓝色部分,this.getClass()方法可以得到了当前类的Class对象,也可以用ParseProperties.class.getClass()方法来实现同样的效果。之后调用其getResourceAsStream("database.properties")方法来解析配置文件。getResourceAsStream()方法解析文件时候的相对路径是当前类的包路径。
4、推荐采用第二种方法,当然这两种方法都是支持移植的,但是第二种方法更灵活一些!
http://blog.youkuaiyun.com/huangyunzeng2008/article/details/5940808