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); } }
  • 相关阅读:
    Saltstack
    搭建中小规模集群之rsync数据同步备份
    Python开发【第七篇】:面向对象二
    批量管理
    inotify
    Python开发【第六篇】:面向对象
    网络文件系统NFS
    Linux基础介绍【第九篇】
    Linux基础介绍【第八篇】
    Linux基础介绍【第七篇】
  • 原文地址:https://www.cnblogs.com/expiator/p/9108461.html
Copyright © 2011-2022 走看看