zoukankan      html  css  js  c++  java
  • classpath路径和properties

      在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();
    }
  • 相关阅读:
    Java多线程
    http网页请求状态码
    C++文件读写
    算法训练 最大的算式
    算法训练 2的次幂表示
    线段树- 算法训练 操作格子
    Prim算法(最小生成树)
    Kruskal算法(最小生成树)
    Dijkstra算法(最短路)
    HDU5692 dfs + 线段树维护区间最大值
  • 原文地址:https://www.cnblogs.com/juaner767/p/5778875.html
Copyright © 2011-2022 走看看