zoukankan      html  css  js  c++  java
  • 读取指定路径的Properties文件

    1.读取项目内的properties文件,项目内的properties文件一般都放在resource文件夹下面,

    通过getClassLoader().getResourceAsStream()来获取取InputStream。

    代码如下:

        Properties    props = new Properties();
        String PATH="jdbc.properties";
        InputStream in = PropertyTest.class.getClassLoader().getResourceAsStream(PATH);
        props.load(in);
        String value=props.getProperty("user");

    2.读取指定路径的properties文件,通过BufferedInputStream来获取流。这种方法,可以获取项目工程外的properties文件。

    代码如下:

      Properties    props = new Properties();
      String PATH="E:\JavaDemo\src\main\resource\jdbc.properties";
      InputStream in = new BufferedInputStream(new FileInputStream( PATH ));
      props.load(in);
      String value=props.getProperty("user");

    3.常用的工具类如下所示:

    public class PropertyUtil {
    //将要读取的properties的文件名
    private static String propertiesFileName="jdbc.properties"; private static final Logger logger = Logger.getLogger(PropertyUtil.class); private static Properties props= new Properties(); static{ logger.info("执行静态代码块loadProps(),保存在jvm中,避免多次执行。"); loadProps(); } synchronized static private void loadProps(){ logger.info("开始加载properties文件内容......."); InputStream in = null; try { //       <!--第一种,通过类加载器进行获取properties文件流,路径为相对路径--> in = PropertyUtil.class.getClassLoader().getResourceAsStream(propertiesFileName); //       <!--第二种,通过类进行获取properties文件流--> //in = PropertyUtil.class.getResourceAsStream("propertiesFileName"); props.load(in); } catch (FileNotFoundException e) { logger.error("properties文件未找到"); } catch (IOException e) { logger.error("出现IOException"); } finally { try { if(null != in) { in.close(); } } catch (IOException e) { logger.error("properties文件流关闭出现异常"); } } logger.info("加载properties文件内容完成..........."); } public static String getProperty(String key){ if(null == props) { loadProps(); } return props.getProperty(key); } public static String getProperty(String key, String defaultValue) { if(null == props) { loadProps(); } return props.getProperty(key, defaultValue); } }
  • 相关阅读:
    8 盒子模型
    7 display属性
    如何提高运维价值体系
    Python学习之OS模块初识
    7、MongoDB学习之游标
    Python 学习之文件对象的属性和方法简介
    Python集合set()操作详解
    Python中的字典介绍
    Python序列之元组
    Python序列之列表
  • 原文地址:https://www.cnblogs.com/expiator/p/9108461.html
Copyright © 2011-2022 走看看