Java学习笔记 - Properties类

本文介绍了Java中Properties类的基本用法,包括如何以键值对形式存储数据,加载和存储配置文件,以及如何从配置文件中读取和设置属性。示例代码展示了如何创建Properties对象,设置键值对,并将数据保存到mysql.properties文件中,同时演示了加载文件并打印键值对以及获取特定键的值的过程。
摘要由CSDN通过智能技术生成

Properties类简单介绍

1、Properties 类以key-value(键值对)形式存放数据

格式为:

        键=值

        键=值

注意:键值对不能有空格,值不需要加引号,默认类型为String

2、key不允许重复,value可以重复,都可以取任意类型的数据,但是都不能为null

3、主要用于从 xxx.properties 文件中加载数据到Properties类对象中进行读取和修改,用作配置文件


 

 Properties 类的常用方法:

load:加载配置文件的键值对到Properties对象

list:将数据显示到指定设备

getProperty(key):根据键获取值

setProperty(key,value):设置键值对到Properties对象

store:将Properties中的键值对存储到配置文件中,在idea软件中,保存信息到配置文件如果含有中文,会保存为对应的unicode码值

代码示例:

import java.io.*;
import java.util.Properties;

/**
 * 使用Properties 类来 保存 、 读取 mysql.properties 文件
 */
public class Properties02 {
    public static void main(String[] args) throws IOException {

        //1. 创建Properties 对象
        Properties properties = new Properties();

        //设置键值对k-v到Properties对象
        properties.setProperty("ip", "196.168.1.1");
        properties.setProperty("user", "root汤姆");//注意,保存时,默认是中文的 unicode码值
        properties.setProperty("pwd", "888888");

        //将k-v 存储文件中
        properties.store(new FileOutputStream("src\\mysql.properties"), null);//注意保存时,默认是中文的 unicode码值
        //设置保存数据的编码方式
//        properties.store(new OutputStreamWriter(new FileOutputStream("src\\mysql.properties"), "gbk"), null);
        System.out.println("保存配置文件成功~");

        //2. 加载指定配置文件
//        properties.load(new FileReader("src\\mysql.properties"));//字符方式
//        properties.load(new FileInputStream("src\\mysql.properties"));//字节方式
        properties.load(new InputStreamReader(new FileInputStream("src\\mysql.properties"), "gbk"));//指定字符编码方式
        //3. 把k-v显示控制台
        properties.list(System.out);
        //4. 根据key 获取对应的值
        System.out.println("====根据key 获取对应的值====");
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名=" + user);
        System.out.println("密码是=" + pwd);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值