Java高级Day35-Properties

102.Properties类

public class Properties01 {
    public static void main(String[] args) throws IOException{\
        //读取mysql.properties 文件,并得到ip,user 和 pwd
        BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
        String line = "";
        while((line = br.readLine()) != null){//循环读取
            String[] split = line.split("=");
            System.out.println(split[0] + "值是:" + split[1]);
        }
        br.close();
    }
}
//可以实现,但不方便
Properties读取,修改,创建文件

配置文件格式: 键=值

注意:键值对不需要有空格,值不需要用引号引起来,默认类型是String

Properties的常见方法:

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

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

  3. getProperty(key):根据键获取值

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

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

案例:

//1.使用Properties类完成对mysql.properties的读取
public class HelloJava {
    public static void main(String[] args) throws Exception {
        //1.创建Properties对象
        Properties properties = new Properties();
        //2.加载指定配置文件
        properties.load(new FileReader("src\\mysql.properties"));
        //3.把k-v显示到控制台
        properties.list(System.out);
        //4.根据key获得对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名=" + user);
        System.out.println("密码=" + pwd);
    }
}
//2.使用Properties类添加key-val到新文件mysql2.properties中
public class HelloJava {
    public static void main(String[] args) throws Exception {
        //创建Properties对象
        Properties properties = new Properties();
        //创建文件
        //若该文件没有key,就是创建
        //若文件有key,就是修改
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");
        properties.setProperty("pwd","abc111");
        //将k-v存储到文件中
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);//null代表注释
        System.out.println("保存配置文件成功");
    }
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值