Java--读/写Properties配置文件

1.Properties文件的创建
创建新properties文件
或者
在这里插入图片描述
结果
创建成功
2.properties类与properties配置文件
我们平时可以通过java中的properties类创建对象对properties文件中的内容进行读写操作。
properties类继承自Hashtable类并实现了Map接口,也是使用一种键值对的形式来保存属性集,properties的键和值都是字符串类型。

3.Properties中的主要方法
3.1

public synchronized void load(InputStream inStream) throws IOException {
load0(new LineReader(inStream));
}
//load()将.properties属性文件对应的文件输入流,加载属性列表到Properties类对象。

使用方法:
File IO
可以使用File Stream的经典方式来读文件,然后解析。

			//实例化对象
 			Properties properties = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/a.properties"));
            properties.load(in);

这种实现方法上需要注意的就是传递文件路径时要传递相对路径(并且properties文件要在此类文件下的子目录中),如果properties文件和类文件分别在不同的目录中/路径中,那么传递的文件路径必须从两个文件相同的父目录开始。

例如:
在这里插入图片描述
需要传递:src/main/resources/a.properties
否则会报错,显示找不到指定文件

ClassLoader
采用classLoader的方式主要是通过它的grtResourceAsStream方法来实现加载properties文件。


            Properties properties = new Properties();
//            InputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/a.properties"));
            InputStream in = test.class.getClassLoader().getResourceAsStream("a.properties");
            properties.load(in);

使用classLoader可以直接传递fileName。
但是在下面这种情况下就会出错;
例如:
在这里插入图片描述
3.2

public void store(OutputStream out, String comments)
throws IOException
{
store0(new BufferedWriter(new OutputStreamWriter(out, “8859_1”)),
comments,
true);
}
//这个方法将properties类对象的属性保存到输出流中。

			Properties properties = new Properties();
            //保存属性到b.properties文件
            FileOutputStream outputStream = new FileOutputStream("b.properties",true);//true表示追加
            properties.setProperty("iphone","11");
            properties.setProperty("ipad","2018");
            properties.store(outputStream,"test");
            outputStream.close();

3.3 getProperty/setProperty
这两个方法分别是获取和设置属性信息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值