日期:2014-05-20  浏览次数:20794 次

如何读取war包中的properties文件,不使用web请求上下文的方式实现
如何读取war包中的properties文件,不使用web请求上下文的方式实现,
项目需求,我想在java project项目中,写个类可以读取war包中的配置文件信息
有什么好的办法呀?

请高手解惑,不胜感激!!!

------解决方案--------------------
Java code

执行前需要将sms.properties文件放在src目录。。

package com.test.impt;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    // 配置文件名称
    private static final String CONFIG_PROPERTIES_FILE = "sms.properties";
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        try {
            Properties props = loadProperties(filePath + CONFIG_PROPERTIES_FILE);
            System.out.println(props.getProperty("dx.server.host")); // 成功输出
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Properties loadProperties(String propertiesFile)
            throws Exception {
        Properties props = null;
        // propertiesFile = getPropertiesFile(propertiesFile);

        // ----------------------------
        // ...and if so, then load the values from that external file
        InputStream in = null;
        try {
            in = new FileInputStream(propertiesFile);
            props = new Properties();
            props.load(in);
        } catch (Exception e) {
            props = null;
        } finally {
            if (in != null)
                in.close();
        }
        return props;
    }
}

------解决方案--------------------
Java code

还有一种方法。。代码量更少的。。
package com.test.impt;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    // 配置文件名称
    private static final String CONFIG_PROPERTIES_FILE = "sms.properties";

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        InputStream is = ClassLoader.getSystemResourceAsStream(CONFIG_PROPERTIES_FILE);
        try {
            Properties props = loadPropertiesFileStream(is);
            System.out.println(props.getProperty("dx.server.host")); // 成功输出
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Properties loadPropertiesFileStream(InputStream is)
            throws Exception {
        Properties props = null;
        try {
            props = new Properties();
            props.load(is);
        } catch (Exception e) {
            props = null;
        } finally {
            if (is != null)
                is.close();
        }
        return props;
    }
}