java Properties 文件操作类简单封装

package com.example.demo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesManager {
    private Properties properties;
    private File file;

    private PropertiesManager() {
        getProperties();
    }

    public PropertiesManager(String fileName) {
        this(new File(fileName));
    }

    public PropertiesManager(File file) {
        this();
        if (!(file != null && file.exists() && file.isFile() && file.getName().endsWith(".properties"))) {
            throw new IllegalArgumentException("无效文件!");
        }
        this.file = file;
        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Properties getProperties() {
        if (properties != null) {
            return properties;
        } else {
            properties = new Properties();
        }
        return properties;
    }

    public Object setProperty(String key, String value) {
        return properties.setProperty(key, value);
    }

    public Properties set(String key, String value) {
        properties.setProperty(key, value);
        return this.properties;
    }

    public boolean flush() {
        return flush("");
    }

    public boolean flush(String desc) {
        try {
            properties.store(new FileOutputStream(file), desc);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

使用方法:

String fileName = "application.properties";
            PropertiesManager propertiesManager = new PropertiesManager(fileName);
            propertiesManager.setProperty("dataSourceFilePath", "E:\\dev\\aria2\\aria2\\log.txt");
//            propertiesManager.set("key1","value2").set("key2","value2").flush();
            propertiesManager.flush();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值