java 获取 classpath下的配置文件

一 获取 prop属性文件:

/**
 * 读取属性文件
 * Created by lg on 2017/2/3.
 */
public class LoadPropertiesFile {

    public static Map<String,String> loadPropFile(String filePath) {

        Map<String, String> map = new HashMap<String,String>();

        // 获取资源文件
        InputStream is = LoadPropertiesFile.class.getClassLoader().getResourceAsStream(filePath);
        //属性列表
        Properties prop = new Properties();

        try {
            prop.load(is);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Set<Map.Entry<Object, Object>> set = prop.entrySet();
        Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
        String key = null;
        String value = null;
        while (iterator.hasNext()) {
            Map.Entry<Object, Object> entry = iterator.next();
            key = String.valueOf(entry.getKey());
            value = String.valueOf(entry.getValue());
            //对取出的值进行非空处理
            key = key == null? null :key.trim().toUpperCase();
            value = value == null? null :value.trim().toUpperCase();
            map.put(key, value);
        }
        return map;
    }
}

二 获取普通文件

URL url = YourClass.class.getClassLoader().getResource("extObj.txt"); File file = new File(url.getFile());

三 获取文件输入流

InputStream in = YourClass.class.getClassLoader().getResourceAsStream(fileName);

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0