Properties

简介: Properties

Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式


1.掌握使用properties类读取属性文件中的键值对信息


1.load 方法读取属性文件

public class PropertiesTest1 {
    public static void main(String[] args) throws Exception {
        // 1.创建一个Properties对象出来(键值对集合,空容器)
        Properties properties=new Properties();
        System.out.println(properties);//{}
 
        // 开始加载属性文件中的键值对数据到properties对象中去
        properties.load(new FileReader("properties-xml-log-app\\src\\User.properties"));
        System.out.println(properties);
 
        // 3.根据建取值
        System.out.println(properties.getProperty("张无忌"));
 
 
    }
}


2.掌握使用properties类向属性文件中输入键值对信息


1.setProperty方法 存储键值对数据

2.store方法 把properties对象值的键值对数据存入到属性文件中去

import java.io.FileWriter;
import java.util.Properties;
 
public class PropertiesTest2 {
    public static void main(String[] args) throws Exception {
        // 1.创建Properties对象出来,先用它存储一些键值对数据
        Properties properties=new Properties();
        properties.setProperty("张无忌","22");
        properties.setProperty("张无","122");
        properties.setProperty("张","221");
 
        // 2.把properties对象值的键值对数据存入到属性文件中去
        properties.store(new FileWriter("properties-xml-log-app\\src\\User.properties" ),"Hello World");
 
    }
}


3.案例


读取属性文件,判断是否存在 彬,存在年龄改成18

1.创建一个properties对象来接受数据

2.读取属性文件

3.判断是否存在彬,存在,将年龄改为18 (通过判断是否存在彬这个键 来判断)

4.把输出回properties文件

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;
 
public class PropertiesTest3 {
    public static void main(String[] args) throws Exception {
        // 目标:读取属性文件,判断是否存在 彬 ,存在年龄改成18
 
         /* 1.创建一个Properties对象来接收数据
            2. 读取属性文件
            3.判断是否存在彬,存在,将年龄改为18
            4.把输出回文件
                        */
 
        // 1.创建一个Properties对象来接收数据
        Properties properties=new Properties();
 
        // 2.读取属性文件
        properties.load(new FileReader("User.txt"));
        System.out.println(properties);
 
        // 3.判断是否存在彬,存在,将年龄改为18
        // 通过判断是否存在键 来判断
      if ( properties.containsKey("彬")){
          properties.setProperty("彬","18");
      }
 
      // 4.输出到文件中去
        // new FileWriter 创建一个字符输出流管道
        properties.store(new FileWriter("User.txt"),"Hello World");
 
 
 
 
 
    }
}
目录
相关文章
|
14天前
|
Java
Properties类的使用
本文介绍了Java中Properties类的使用,它继承自Hashtable,用于处理属性文件。Properties对象可以保存键值对,并且能够从输入流加载或保存到输出流。文章展示了如何读取和写入properties文件,包括使用`setProperty`和`getProperty`方法来设置和获取属性值,以及使用`list`方法打印属性到控制台。同时,还解释了Properties类底层使用的哈希表结构,并提到了字符编码转换问题,特别是在处理中文时会转换成unicode编码。
|
XML 存储 安全
一文带你全面了解Properties类
一文带你全面了解Properties类
159 0
一文带你全面了解Properties类
|
XML 移动开发 Java
详解log4j.properties配置
详解log4j.properties配置
|
机器学习/深度学习 关系型数据库 Oracle
xtt.properties
Reduce Transportable Tablespace Downtime using Incremental Backups (Doc ID 1389592.1) Properties file for xttdriver.
968 0
|
Java Spring
|
Windows Linux
|
Windows Linux
|
Java 网络架构