zoukankan      html  css  js  c++  java
  • 读取properties属性文件

    1、通过类加载器加载

    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Chapter8/test.properties"); 
    Properties p = new Properties();  
    p.load(inputStream );

    2、通过文件系统加载

    InputStream inputStream = new FileInputStream("Chapter8/test.properties"); 

    以下是获取当前工程路径的方法:

    注意:

    Class.getResource(String path) 

    path不以’/'开头时,默认是从此类所在的包下取资源; 

    path以’/'开头时,则是从ClassPath根下获取;

    Class.getClassLoader().getResource(String path)

    path不能以’/'开头时;

    path是从ClassPath根下获取;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            String[] path = new String[5];
            path[0] = Thread.currentThread().getContextClassLoader()
                    .getResource("Chapter8/test.properties").getPath();
            path[1] = this.getClass().getClassLoader()
                    .getResource("Chapter8/test.properties").getPath();
            path[2] = this.getClass().getResource("/Chapter8/test.properties")
                    .getPath();
            path[3] = this.getClass().getResource("test.properties")
                    .getPath();
            path[4] = ClassLoader.getSystemResource("Chapter8/test.properties")
                    .getPath();
            for (int i = 0; i < path.length; i++) {
                System.out.println(path[i]);
            }
    }

    得到的文件路径是:

    /D:/Program/Java/NecessaryLearning/bin/Chapter8/test.properties
    /D:/Program/Java/NecessaryLearning/bin/Chapter8/test.properties
    /D:/Program/Java/NecessaryLearning/bin/Chapter8/test.properties
    /D:/Program/Java/NecessaryLearning/bin/Chapter8/test.properties
    /D:/Program/Java/NecessaryLearning/bin/Chapter8/test.properties

      

  • 相关阅读:
    jvm的那些设置参数你都知道吗
    进程之间究竟有哪些通信方式
    从零开始带你成为JVM实战高手
    java 面试题目(java高级架构)
    面试要点补充
    Paxos算法与Zookeeper分析,zab (zk)raft协议(etcd) 8. 与Galera及MySQL Group replication的比较
    一文搞懂Raft算法
    Python 循环语句
    Python 条件语句
    Python 运算符
  • 原文地址:https://www.cnblogs.com/SaraMoring/p/5604635.html
Copyright © 2011-2022 走看看