zoukankan      html  css  js  c++  java
  • 2017.6.29 java读取.properties配置文件的几种方法

    参考来自:http://www.cnblogs.com/s3189454231s/p/5626557.html

    关于路径的解释:http://blog.csdn.net/bluishglc/article/details/38753047

    官方文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29

    0 获取InputStream的几种方式

    项目结构:

     0 //PropertiesWay.class.getResourceAsStream()最终调用是ClassLoader.getResourceAsStream()
    1 InputStream inStream1 = PropertiesWay.class.getClassLoader().getResourceAsStream("../resource/test.properties"); 3 InputStream inStream2 = ClassLoader.getSystemResourceAsStream("com/lyh/resource/test.properties"); 4 InputStream inStream3 = new FileInputStream(new File("E:/lyh/file/workspace/ReadPropertiesFile/src/com/lyh/resource/test.properties"));
    5 //servlet环境下还可以用context 6 //InputStream inStream4 = context.getResourceAsStream("/WEB-INF/config/login.conf"); 7 //InputStream in = context.getResourceAsStream("filePath"); 8 9 ////通过url获取 10 //URL url = new URL("path"); 11 //InputStream inStream5 = url.openStream();

    关于类名.class.getClassLoader.getSystemResourceAsStreamClassLoader.getSystemResourceAsStream中,路径的解释可以参考:http://blog.csdn.net/bluishglc/article/details/38753047

    简而言之就是:

    类名.class.getClassLoader.getSystemResourceAsStream(path)中填写的path:以这个类的所在路径(这里是com.lyh.test)为基础。

    ClassLoader.getSystemResourceAsStream(path)中填写的path:以classpath的路径(这里是src)为基础。

    最重要的是:这里全是相对路径,所以开头不要加“/”。

    如果不确定当前的classpath路径,可以通过如下代码获取:

    1 PropertiesWay.class.getClassLoader().getResource("").toString();

    1 通过jdk提供的java.util.Properties类

    在操作之前,首先要读取配置文件,有两种方式:load和loadFromXML。

    1.1 load

    load有两个方法的重载:load(InputStream inStream)、load(Reader reader),所以,可根据不同的方式来加载属性文件。

    1.1.1 load(InputStream inStream)

    1 p.load(inStream);    
    2 System.out.println(p.getProperty("name"));  
    3 p.setProperty("name", "inStream changed");

    1.1.2 load(Reader reader)

    1.2 loadFromXML

    2.通过java.util.ResourceBundle类读取

    2.1 通过ResourceBundle.getBundle()

    ResourceBundle是一个抽象类,这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可。

    1 ResourceBundle resource = ResourceBundle.getBundle("com/mmq/test");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可    
    2 String key = resource.getString("username");  

    2.2 从InputStream中读取

    获取inputStream的方法和前面load中介绍的一样。

    1 ResourceBundle resource = new PropertyResourceBundle(inStream); 
    2 String key = resource.getString("username");
  • 相关阅读:
    ActiveSync合作关系对话框的配置
    WINCE对象存储区(object store)
    Wince 隐藏TASKBAR的方法
    Wince输入法换肤换语言机制
    poj 3080 Blue Jeans 解题报告
    codeforces A. Vasily the Bear and Triangle 解题报告
    hdu 1050 Moving Tables 解题报告
    hdu 1113 Word Amalgamation 解题报告
    codeforces A. IQ Test 解题报告
    poj 1007 DNA Sorting 解题报告
  • 原文地址:https://www.cnblogs.com/lyh421/p/7094134.html
Copyright © 2011-2022 走看看