zoukankan      html  css  js  c++  java
  • Java读取.properties配置文件

    一、介绍

    Properties文件在Java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值"

    二、读取

    这里我采用的是getResourceAsStream的文件读取方法

    如果想要使用这个方法,则需要了解一些基本使用信息:

    1、读取文件路径范围:只局限于工程的源文件中

    2、文件访问形式:带"/"是绝对路径,不带"/"是相对路径

    3、读取文件类型:主要为:.properties文件,.xml文件

    三、使用

    主要方法有:

    1、 load ( InputStream  inStream) :从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如的 beans.properties 文件)进行装载来获取该文

    件中的所有键 - 值对。

    2、 setProperty ( String  key, String  value) :调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

    3、 getProperty ( String  key) :用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

    4、 store ( OutputStream  out, String  comments) :以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素

    对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

    5、 clear ():清除所有装载的 键 - 值对。该方法在基类中提供。



    java项目配置文件存放位置:

    Maven项目配置文件存放位置:

    配置文件:

    className = edu.nf.ch02.impl.Sub

    java代码:

    public class Main {
    
        public static void main(String[] args) throws IOException {
            //创建Properties对象
            Properties prop = new Properties();
            //读取classPath中的properties文件
            prop.load(Main.class.getClassLoader().getResourceAsStream("bean.properties"));
            //根据键取出值
            String className = prop.getProperty("className");
            System.out.println(className);
            
        }
    }

    运行结果:

    封装的PropertiesUtil工具类:

    public class PropertyUtil {
    
        private static Properties prop = new Properties();
    
        static {
            try {
                prop.load(PropertyUtil.class.getClassLoader().getResourceAsStream("calculator.properties"));
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    
        /**
         * 根据Name获取Property
         * @param name
         * @return
         */
        public static String getProperty(String name) {
            return prop.getProperty(name);
        }
    
        /**
         * 获取所有的Property
         * @return
         */
        public static List<String> getBeanFactoryClass() {
            List<String> list = new ArrayList<>();
            Set<String> keys = prop.stringPropertyNames();
            for (String key : keys) {
                list.add(prop.getProperty(key));
            }
            return list;
        }
    }
  • 相关阅读:
    华为交换机LACP模式(动态)链路聚合配置示例
    H3C交换机配置链路聚合
    ODBC数据源的作用及配置
    SQL Server Management Studio与SQL Server Configuration Manager
    SQL Server 2008 允许远程连接的解决方法
    多实例并存的技术限制,与原因
    多个SQL server实例
    SQL Server实例
    Oracle
    Burp Suite Professional更换闪退日记
  • 原文地址:https://www.cnblogs.com/hhmm99/p/9803119.html
Copyright © 2011-2022 走看看