在Java程序中,一般情况下使用绝对路径还是相对路径都不太合适,因为Java程序的jar包所放的位置不确定,执行java程序时当前的路径也不确定,所以不合适。一般在Java程序中我们会把资源放到classpath中,然后使用classpath路径查找资源。

1.获取classpath中的资源(InputStream)

public class Demo1 {
    static Properties properties;
    static{
        properties = new Properties();
        try {
            Class clazz = Demo1.class;
            // 开头的'/'表示classpath的根目录,这个是表示从classpath的根目录中开始查找资源,如果开头没有'/',表示从当前这个class所在的包中开始查找
            InputStream inputestream = clazz.getResourceAsStream("/db.properties");
            properties.load( inputestream);
        } catch (IOException e) {
        }
    }
    @Test
    public void DBUtil(){
        System.out.println("username:"+properties.getProperty("username")+
                " password:"+properties.getProperty("password"));
    }
}    

2.Properties配置文件

加载配置文件

public class DBUtil {
    
    static Properties properties = new Properties();
    
    static{
        try {
            Class clazz = DBUtil.class;
            InputStreamReader fileReader =
            new InputStreamReader(clazz.getResourceAsStream("/db.properties"));
            properties.load(fileReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getUserName(){
        String userName =properties.getProperty("userName");
        return userName;
    }
    
    public static String getPassword(){
        return    properties.getProperty("password");
    }
    public static void main(String[] args) {
        System.out.println("用户名:"+ getUserName());
        System.out.println("密码: "+  getPassword());
    }
}

写配置文件

public static void testStoreProperties() throws Exception {
    // 准备配置信息
    Properties properties = new Properties();
    properties.setProperty("name", "李四");
    properties.setProperty("age", "20");

    // 准备
    OutputStream out = new FileOutputStream("d:/my.properties");
    String comments = "这是我的配置文件";

    // 写出去
    properties.store(out, comments);
    out.close();
}

 

 posted on 2016-08-17 10:17  十三弦  阅读(7319)  评论(0编辑  收藏  举报