美文网首页
java读取jar包内的配置文件

java读取jar包内的配置文件

作者: alexlee666 | 来源:发表于2018-09-13 15:16 被阅读0次

    有时候我们会将一些配置信息写在配置文件(.properties文件)里,并放在java project的resources路径下(jar内部),然后程序内部需要去读取配置文件中的配置项(即属性)。下面给出实现方法:

    注:读取jar外部的配置文件请访问:  https://www.jianshu.com/p/128857aded84     

    step 1. 在project下的src/main/resources/下新建配置文件test.properties

    step 2. 参考如下代码:

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import javax.naming.Context;

    import java.io.*;

    import java.util.Properties;

    public class PropertiesReader {

        protected final static Loggerlogger = LoggerFactory.getLogger(PropertiesReader.class);

        public String readProperties(String propertiesName) {

            logger.info("start reading properties file.");

            Properties prop =new Properties();

            InputStream inputStream =null;

            //读取src/main/resources/下的配置文件test.properties

            try {

                // 此处的getClassLoader不能少,否则回报nullpointer异常           

                 inputStream =this.getClass().getClassLoader().getResourceAsStream("test.properties");

                // 加载属性列表

                prop.load(inputStream);

                instanceName = prop.getProperty(propertiesName);

                inputStream.close();

            }catch (FileNotFoundException e) {

                e.printStackTrace();

            }catch (IOException e) {

                e.printStackTrace();

            }

            return instanceName;

        }

    }


    另外,将配置文件打入jar包的方法可以参考:https://www.jianshu.com/p/126390556e37

    相关文章

      网友评论

          本文标题:java读取jar包内的配置文件

          本文链接:https://www.haomeiwen.com/subject/knmwgftx.html