java 读取项目中文件属性

java 读取项目中文件属性最简单的一种方法,其他方法自行百度

package com.xxx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

public class PropertyUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertyUtil.class);

    private static Properties props;

    public static Properties getConfig(String fileName){
        props = new Properties();
        InputStream in;
        BufferedReader bf = null;
        try{

            // 第一种,通过类加载器进行获取properties文件流 fileName("resource/resource.properties")
            in = PropertyUtil.class.getClassLoader().getResourceAsStream(fileName);

            // 第二种,通过类进行获取properties文件流 filePathe("/resource/resource.properties"),前边多一个 '/'
            //in = PropertyUtil.class.getResourceAsStream("/resource/resource.properties");

            if (in != null) {
                bf = new BufferedReader(new InputStreamReader(in));
            }
            props.load(bf);

        } catch (FileNotFoundException e) {
            logger.error(fileName+"文件未找到");
        } catch (IOException e) {
            logger.error("出现IOException");
        }finally {
            if(null != bf){
                try {
                    bf.close();
                } catch (IOException e) {
                    logger.error("jdbc.properties文件流关闭出现异常");
                }
            }
        }
        return props;
    }

    public static String getProperty(String fileName,String key){
        if(null == props) {
            getConfig(fileName);
        }
        return props.getProperty(key);
    }


    public static void main(String[] args){
        //Properties prop = PropertyUtil.getConfig("classpath:resource/resource.properties");
        //String url = prop.getProperty("ZHL_URL");
        String url = PropertyUtil.getProperty("resource/resource.properties", "ZHL_URL");
                System.out.println(url);
    }
}

你可能感兴趣的:(Java,java,获取文件属性)