集册 Java实例教程 包属性来自文件META

包属性来自文件META

欢马劈雪     最近更新时间:2020-01-02 10:19:05

483
软件包属性来自文件META-INF / config / full / package / name / config.properties

/**

 * Copyright (c) 2012-2014, Steven Atkinson. All rights reserved.

 */

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;/** 时   代     Java  公  众  号 - nowjava.com 提供 **/

import java.net.URL;

import java.util.Properties;


public class Main{

    /**

     * Package properties come from the file <code>META-INF/config/full/package/name/config.properties</code>

     * @param pkg the package for which we need to load properties

     * @return a non-null Properties object containing package-specific properties

     */

    public static Properties loadPackageProperties(Package pkg) {

        final String packageName = pkg.getName();

        return loadResourceAsProperties(String.format(

                "META-INF/config/%s/%s.%s", packageName.replace('.', '/'),

                "config", "properties"));

    }

    private static Properties loadResourceAsProperties(

            String resourceLocation) {

        final ClassLoader classLoader = Thread.currentThread()/**from 时 代      J a v a   公   众 号 - nowjava.com**/

                .getContextClassLoader();

        BufferedReader in = null;

        final Properties properties = new Properties();

        try {

            final URL resource = classLoader.getResource(resourceLocation);

            if (resource != null) {

                in = new BufferedReader(new InputStreamReader(

                        resource.openStream(), UTF8.charset()));

                properties.load(in);

            }

        } catch (Exception e) {

            // logger.log(Level.INFO, String.format("Failed to load resource %s from classpath.",

            //                                      resourceLocation), e);

        } finally {

            if (in != null) {

                try {

展开阅读全文