Properties类的用法

Properties的常用方法:

1.setProperty(String key, String value)
调用 Hashtable 的方法 put。

2.getProperty(String key)
用指定的键在此属性列表中搜索属性

3.getProperty(String key, String defaultValue)
用指定的键在属性列表中搜索属性。

4.load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。

5.load(Reader reader)
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。

6.loadFromXML(InputStream in)
将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。

7.store(OutputStream out, String comments)
以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

8.store(Writer writer, String comments)
以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。

9.storeToXML(OutputStream os, String comment)
发出一个表示此表中包含的所有属性的 XML 文档。

10.storeToXML(OutputStream os, String comment, String encoding)
使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。

操作文件

先定义一个工厂类,载入文件,再操作

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

public class PropertyFactory {

    private static final Logger logger = LoggerFactory.getLogger(PropertyFactory.class);
    private static final Properties prop = new Properties();

    static {
        try {
            prop.load(PropertyFactory.class.getClassLoader().getResourceAsStream("leaf.properties"));
        } catch (IOException e) {
            logger.warn("Load Properties Ex", e);
        }
    }

    public static Properties getProperties() {
        return prop;
    }

    public static Integer getInteger(String key, Integer defaultValue) {
        String value = prop.getProperty(key);
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            logger.warn(key + " is not Integer value,return default value:" + defaultValue);
            return defaultValue;
        }
    }

    public static Long getLong(String key, Long defaultValue) {
        String value = prop.getProperty(key);
        try {
            return Long.parseLong(value);
        } catch (Exception e) {
            logger.warn(key + " is not Integer value,return default value:" + defaultValue);
            return defaultValue;
        }
    }

    public static String getString(String key, String defaultValue) {
        String value = prop.getProperty(key, defaultValue);
        return value;
    }

    public static Boolean getBoolean(String key, Boolean defaultValue) {
        String value = prop.getProperty(key);
        try {
            return Boolean.parseBoolean(value);
        } catch (Exception e) {
            logger.warn(key + " is not Boolean value,return default value:" + defaultValue);
            return defaultValue;
        }
    }
}
// 载入文件也可以这样:
//Properties properties = new Properties();
//properties.load(new FileInputStream(new File(FILE_PATH)));
//long timestamp = properties.getProperty("maxTimestamp");

用法

Properties properties = PropertyFactory.getProperties();
String consulAddress = properties.getProperty(Constants.CONSUL_ADDRESS);

常见操作

为properties对象添加属性和获取值

@Test   
public void setAndGetProperty() {
      Properties pro = new Properties();
      //设置值
      pro.setProperty("driver", "com.mysql.jdbc.Driver");
      pro.setProperty("url", "jdbc:mysql///user");
      pro.setProperty("user", "root");
      pro.setProperty("password", "451535");
      //获取值:
      //1、getProperty(String key)方法  通过键获取值
      String str= pro.getProperty("driver");
      System.out.println(str);
      //2、getProperty(String key, String defaultValue)重载方法
      //当properties对象中没有所指定的键值时,显示给定的默认值
      String str2=pro.getProperty("driver", "没有该值");
      String str3=pro.getProperty("haha", "没有该值");
      System.out.println(str2);
      System.out.println(str3);

}

以properties配置文件格式写入到硬盘中的某个文件夹(本例写入到D盘的others文件夹中):

@Test
public void storePropertiesToHardFile() throws FileNotFoundException, IOException{
             Properties pro=new Properties();
             pro.setProperty("driver", "com.mysql.jdbc.Driver");
             pro.setProperty("url", "jdbc:mysql///user");
             pro.setProperty("user", "root");
             pro.setProperty("password", "451535");
             //1.通过字节流的形式
             //store(OutputStream out, String comments)
             //outputStream:字节输出流   comments:配置文件说明
             pro.store(new FileOutputStream(new File("d:/others/jdbc.properties")), "数据库配置文件");

             //2.通过字符流的形式
             //store(Writer writer, String comments)
             //writer:字符输出流   comments:配置文件说明
             pro.store(new FileWriter("d:/others/jdbc.properties"),  "数据库配置文件");
       }

以XML配置文件格式写入到硬盘中的某个文件夹(本例写入到D盘的others文件夹中):

@Test
public void storeXMLToHardFile() throws FileNotFoundException, IOException{
             Properties pro=new Properties();
             pro.setProperty("driver", "com.mysql.jdbc.Driver");
             pro.setProperty("url", "jdbc:mysql///user");
             pro.setProperty("user", "root");
             pro.setProperty("password", "451535");
             //1.不指定编码  默认为:UTF-8
             //storeToXML(OutputStream os, String comment)
             //因为XML不是文本文件,所以只能用字节流,为不能用字符流
             pro.storeToXML(new FileOutputStream("d:/others/jdbc.xml"), "数据库配置文件");

             //1.不指定编码
          //storeToXML(OutputStream os, String comment)
          //因为XML不是文本文件,所以只能用字节流,为不能用字符流
             pro.storeToXML(new FileOutputStream("d:/others/jdbc2.xml"), "数据库配置文件", "GBK");
       }

以properties和XML配置文件格式写入到应用程序的某个文件夹(本例写入应用程序的classPath类路径下):

public void storeToClassPsth() throws FileNotFoundException, IOException{
             Properties pro=new Properties();
             pro.setProperty("driver", "com.mysql.jdbc.Driver");
             pro.setProperty("url", "jdbc:mysql///user");
             pro.setProperty("user", "root");
             pro.setProperty("password", "451535");
             pro.store(new FileOutputStream("src/jdbc.properties"), "数据库配置文件");
             pro.storeToXML(new FileOutputStream("src/jdbc.xml") , "数据库配置文件");
       }

加载和读取配置文件(以properties文件为例)

public void loadAndReadFile() throws FileNotFoundException, IOException{
             Properties pro=new Properties();
             //通过字节输入流
             //load(InputStream inStream)
             pro.load(new FileInputStream("src/sql.properties"));
             //通过类加载器 获取当前类路径 
             //类路径是指      / bin路径
             pro.load(this.getClass().getResourceAsStream("/sql.properties"));
              pro.load(this.getClass().getClassLoader().getResourceAsStream("sql.properties"));

             //也可以使用当前上下文的类加载器,不用“/”
              pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("sql.properties"));
             //通过字符输入流
             //load(Reader reader)
             pro.load(new FileReader("src/jdbc.properties"));
             System.out.println(pro.get("driver"));
//以上几种加载配置文件的方法都可以使用,此处都列举出来。
       }

参考:https://blog.csdn.net/yelang0/article/details/76449165

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值