读取资源文件信息

读取资源文件

摘要:对资源文件.properties的读写操做web

一. 获取类路径的方式:

  • 获取某个类的位置(编译后的.class文件的位置):
    new Junit().getClass().getResource("").getPath();
  • 获取classpath的位置(在tomcat中完美获取,在weblogic中没法正常获取,在JavaApplication中也能获取):tomcat

    this.getClass().getResource("").getPath();this

  • 获取classpath的位置(该方法在jdk7之后无效):spa

    Thread.currentThread().getContextClassLoader().
    getResource("").getPath();code

二. Properties 类

Properties类主要是对资源文件进行读写操做
它提供了几个主要的方法:对象

  • getProperty ( String key)
    用指定的键在此属性列表中搜索属性。也就是经过参数 key ,获得 key 所对应的 value。blog

  • load ( InputStream inStream)
    从输入流中读取属性列表(键和元素对)。经过对指定的文件(好比说上面的 test.properties 文件)进行装载来获取该文件中的全部键 - 值对。以供 getProperty ( String key) 来搜索。资源

  • setProperty ( String key, String value)
    调用 Hashtable 的方法 put 。他经过调用基类的put方法来设置 键 - 值对。get

  • store ( OutputStream out, String comments)
    以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。input

  • clear
    清除全部装载的 键 - 值对。该方法在基类中提供。

读取资源文件的代码以下:

public void getProperties(){
    //  demo 中获取的资源文件都是放在src下面的,即都会被编译到 classpath 下
    //  若是 properties 文件不放在 classpath 下,使用绝对路径也不能取到文件, 这一点还须要再研究下,
    //  能够用BufferedInputStream(inputStream)方法尝试下
    //  在 getResourceAsStream 中的参数以 "/" 开头,则获取到的是 classpath, 获取资源文件须要本身写上包名, 如代码1
    //  若是参数直接写资源文件的文件名, 则表示资源文件与该类在同一个目录下, 如代码2
    //  若是把获取资源文件做为静态方法, 那么该方法中没法使用对象 this
    //  为了在在静态方法中获取资源文件,能够使用 Obejct.class 来获取一个 Class 对象, 如代码3
    //  getResourceAsStream 只是须要一个 Class 对象, 用 int.class 照样行
        InputStream inputStream = this.getClass().getResourceAsStream("/properties/param.properties"); //代码1 资源文件与类不在同一个包中
    /*
        InputStream inputStream = this.getClass().getResourceAsStream("aram.properties");  //代码2 资源文件与类在同一个包中
        InputStream inputStream = Object.class.getResourceAsStream("aram.properties"); // 代码3 若是当前类是个静态方法,则不能使用代码2,要把this 换成 Object.class()
    */

        Properties properties = new Properties();
        try {
            properties.load(inputStream);   // 把获取的资源文件加载到 Proeprties 类中,而后能够经过 getProperty("key") 获取属性的值
            Enumeration enumeration = properties.propertyNames();   // 获取资源文件中的属性
            while(enumeration.hasMoreElements()){
                String paramName = enumeration.nextElement().toString();
                System.out.println("资源文件中的参数名:" + paramName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

写入资源文件的代码以下:

todo
相关文章
相关标签/搜索