Java 读取配置文件的五种方式

因为是用ServletContext读取文件路径,所以配置文件可以放入在WEB-INFclasses目录中,也可以在应用层级WEB-INF的目录中。

文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。

因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。

具体举例如下:

    //ServletContext.getRealPath(name)读取路径
    private void test1(HttpServletRequest request, HttpServletResponseresponse)  
    throws ServletException,IOException {
       //response.setContentType("text/html;charset=utf-8");
       String path = "/WEB-INF/jdbc_connection.properties"; //读取WEB-INF中的配置文件
       String realPath = getServletContext().getRealPath(path);
       //getServletContext()相当于http://localhost/demo05
       //所以后面的path只需要以应用demo05/开头具体的部署目录路径即可,如上面的/web-in…
       System.out.println(realPath);

       InputStreamReader reader =new InputStreamReader(newFileInputStream(realPath),"utf-8");
       Properties props = new Properties();
       props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码
       String jdbcConValue = props.getProperty("jdbc_con");
       System.out.println(jdbcConValue);

       System.out.println("加载src包下的资源------------------------");
       path = "/WEB-INF/classes/com/test/servlet/jdbc_connection.properties";
       realPath=getServletContext().getRealPath(path);
       System.out.println(realPath);

       reader = new InputStreamReader(new FileInputStream(realPath),"utf-8");
       props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码
       jdbcConValue = props.getProperty("jdbc_con");
       System.out.println("second::"+jdbcConValue);
      
    }

方式二:采用ResourceBundle类读取配置信息,

优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。

缺点:只能加载类classes下面的资源文件,且只能读取.properties文件。

    /**
     * 获取指定.properties配置文件中所以的数据
     * @param propertyName
     *        调用方式:
     *            1.配置文件放在resource源包下,不用加后缀
     *              PropertiesUtil.getAllMessage("message");
     *            2.放在包里面的
     *              PropertiesUtil.getAllMessage("com.test.message");
     * @return
     */
    public static List<String> getAllMessage(String propertyName) {
        // 获得资源包
        ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim());
        // 通过资源包拿到所有的key
        Enumeration<String> allKey = rb.getKeys();
        // 遍历key 得到 value
        List<String> valList = new ArrayList<String>();
        while (allKey.hasMoreElements()) {
            String key = allKey.nextElement();
            String value = (String) rb.getString(key);
            valList.add(value);
        }
        return valList;
    }

方式三:采用ClassLoader方式进行读取配置信息

优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息。

缺点:只能加载类classes下面的资源文件。

    /**获取的是classes路径下的文件
     * 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
     * 缺点:只能加载类classes下面的资源文件。
     * 如果要加上路径的话:com/test/servlet/jdbc_connection.properties
     */
    private static void use_classLoador(){
        //获取文件流
        InputStream is=TestJava.class.getClassLoader().getResourceAsStream("message.properties");

        //获取文件的位置
        String filePath=TestJava.class.getClassLoader().getResource("message.properties").getFile();
        System.out.println(filePath);

    }

修改Properties:

    /**
     * 传递键值对的Map,更新properties文件
     * @param fileName
     *        文件名(放在resource源包目录下),需要后缀
     * @param keyValueMap
     *        键值对Map
     */
    public static void updateProperties(String fileName, Map<String,String> keyValueMap) {
        //InputStream inputStream =  
        //   PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName); //输入流
        String filePath = 
           PropertiesUtil.class.getClassLoader().getResource(fileName).getFile(); //文件的路径
        System.out.println("propertiesPath:" + filePath);
        Properties props = new Properties();
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // 从输入流中读取属性列表(键和元素对)
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            props.load(br);
            br.close();

            // 写入属性文件
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            props.clear();// 清空旧的文件
            for (String key : keyValueMap.keySet())
                props.setProperty(key, keyValueMap.get(key));
            props.store(bw, "");
            bw.close();
        } catch (IOException e) {
            System.err.println("Visit " + filePath + " for updating value error");
        } finally {
            try {
                br.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

方法四:getResouceAsStream

XmlParserHandler.class.getResourceAsStream 与 classloader 的不同之处在于使用的是当前类的相对路径。

BufferedReader br=new BufferedReader( 
  new InputStreamReader(
    XmlParserHandler.class.getResourceAsStream("./rain.xml"),  //./代表当前目录不写也可以    
    "GB2312"
  )
);

方法五:PropertiesLoaderUtils 工具类

Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源。

最大的好处就是:实时加载配置文件,修改后立即生效,不必重启。

    private static void springUtil(){
        Properties props = new Properties();
        while(true){
            try {
                props=PropertiesLoaderUtils.loadAllProperties("message.properties");
                for(Object key:props.keySet()){
                    System.out.print(key+":");
                    System.out.println(props.get(key));
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

转载自:https://www.jianshu.com/p/efdd1a526939