Java读取修改Properties文件

properties文件是我们经常需要操作一种文件,它使用一种键值对的形式来保存属性集。

无论在学习上还是工作上经常需要读取,修改,删除properties文件里面的属性。

本文通过操作一个properties去认识怎样操作properties文件。

Java提供了Properties这个类Properties(Java.util.Properties),用于操作properties文件。

这是配置文件,file.properties

type=mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username=root
password=root
public class PropertiesDemo {
 
    public static final Properties p = new Properties();
    public static final String path = "file.properties";

初始化:

    /**
     * 通过类装载器 初始化Properties
     */
    public static void init() {
        //转换成流
        InputStream inputStream =     
        PropertiesDemo.class.getClassLoader().getResourceAsStream(path);
        try {
            //从输入流中读取属性列表(键和元素对)
            p.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

获取:

    /**
     * 通过key获取value
     * @param key
     * @return
     */
    public static String get(String key) {
        return p.getProperty(key);
    }

修改或者新增:

    /**
     * 修改或者新增key
     * @param key
     * @param value
     */
    public static void update(String key, String value) {
        p.setProperty(key, value);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            //将Properties中的属性列表(键和元素对)写入输出流
            p.store(oFile, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

删除:

    /**
     * 通过key删除value
     * @param key
     */
    public static void delete(String key) {
        p.remove(key);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            p.store(oFile, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

获取所有:

    /**
     * 循环所有key value
     */
    public static void list() {
        Enumeration en = p.propertyNames(); //得到配置文件的名字
        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = p.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
    }

测试:

public static void main(String[] args) {
    PropertiesDemo.init();
 
    //修改
    PropertiesDemo.update("password","123456");
    System.out.println(PropertiesDemo.get("password"));
 
    //删除
    PropertiesDemo.delete("username");
    System.out.println(PropertiesDemo.get("username"));
 
        //获取所有
    PropertiesDemo.list();
}

原文地址:https://www.cnblogs.com/zp-uestc/p/10345010.html