Properties类

目录

Properties类

1 使用传统的方法

2 使用Properties类去实现

Properties的基本介绍

1. 使用 Properties类读文件

2. 使用Properties类添加key-val到新文件

3.  使用Properties类修改文件


Properties类

1 使用传统的方法

public class Properties01 {
    public static void main(String[] args) throws IOException {
        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();

    }
}

2 使用Properties类去实现

Properties的基本介绍

1. 使用 Properties类读文件

public class Properties02 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();

        //加载指定的配置文件
        properties.load(new FileReader("src\\mysql.properties"));

        //把 k-v 显示到指定的控制台
        properties.list(System.out);
        System.out.println("==========");
        
        //根据key获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名="+user);
        System.out.println("密码="+pwd);
    }
}

2. 使用Properties类添加key-val到新文件

public class Properties03 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();

        properties.setProperty("charset","utf-8");
        //保存中文时是保存unicode码值
        properties.setProperty("user", "汤姆");
        properties.setProperty("pwd", "abc111");

        properties.store(new FileOutputStream("src\\msyql2.properties"),null);
        System.out.println("保存配置文件成功~");
    }
}

3.  使用Properties类修改文件

public class Properties02 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();

        //加载指定的配置文件
        properties.load(new FileReader("src\\mysql.properties"));

        //把 k-v 显示到指定的控制台
        properties.list(System.out);
        System.out.println("==========");

        //修改文件
        properties.setProperty("user","Jay");
        properties.setProperty("pwd","6666666");
        properties.store(new FileWriter("src\\mysql.properties"),null);

        //根据key获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名="+user);
        System.out.println("密码="+pwd);

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值