Java(46):Properties工具类

这篇博客详细介绍了Java中PropertiesUtil工具类的实现,包括读取、写入配置文件的方法。在读取配置文件时,博主遇到了通过Class.getResource()和ClassLoader.getResource()定位资源的问题,最终通过指定资源路径解决了直接写入src/main/resources目录下源文件的难题。文章还提供了完整的代码示例,展示了如何按key获取值和获取整个配置信息。

Properties工具类

package com.ciphergateway.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.URL;
import java.util.Properties;


public class PropertiesUtil {
    private static final Logger log= LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    private String propertiesName="";

    public PropertiesUtil(){

    }
    public PropertiesUtil(String filename){
        this.propertiesName=filename;
    }

    /**
     * 按key获取值
     * @param key 键
     * @return value
     */
    public String readProperty(String key){
        Properties pros=new Properties();
        String value="";
        InputStream is=null;
        try{
            //String filePath = PropertiesUtil.class.getClassLoader().getResource(propertiesName).getPath();

            String path = System.getProperty("user.dir");
            String filePath = path + "/src/main/resources/"+propertiesName;
            is = new FileInputStream(filePath);

            is = FileUtil.locateFile(propertiesName).openStream();
            InputStreamReader reader = new InputStreamReader(is,"UTF-8");
            pros.load(reader);
            value=pros.getProperty(key);
            reader.close();
        }
        catch (IOException e){
            e.printStackTrace();
            log.error(e);
        }
        finally {
            try{
                is.close();
            }catch (IOException e){
                e.printStackTrace();
                log.error(e);
            }
        }
        return value;
    }

    /**
     * 获取整个配置信息
     * @return Properties
     */
    public Properties getProperties(){
        Properties pros=new Properties();
        InputStream is =null;
        try{
            //String filePath = PropertiesUtil.class.getClassLoader().getResource(propertiesName).getPath();

            String path = System.getProperty("user.dir");
            String filePath = path + "/src/main/resources/"+propertiesName;
            //String filePath = PropertiesUtil.class.getResource("/"+propertiesName).getPath();
            is = new FileInputStream(filePath);
            InputStreamReader reader = new InputStreamReader(is,"UTF-8");
            pros.load(reader);
            reader.close();
            is.close();

        }catch (IOException e){
            e.printStackTrace();
            log.error(e);
        }
        return pros;
    }

    /**
     * key-value写入配置文件
     * @param key 键
     * @param value 值
     */
    public void writeProperty(String key,String value) throws Exception {
        Properties pros=new Properties();
        InputStream is =null;
        OutputStream os=null;
        String filePath="";
        try{

            String path = System.getProperty("user.dir");
            filePath = path + "/src/main/resources/"+propertiesName;
            //从输入流中读取属性列表(键和元素对)
            is = new FileInputStream(filePath);

            //URL url = FileUtil.locateFile(propertiesName);
            //is = url.openStream();
            InputStreamReader reader = new InputStreamReader(is,"UTF-8");
            pros.load(reader);
            //os = new FileOutputStream(url.getPath());
            os=new FileOutputStream(new File(filePath));
            pros.setProperty(key, value);
            //将此 Properties 表中的属性列表(键和元素对)写入输出流
            pros.store(new OutputStreamWriter(os,"UTF-8"),"Update '" + key + "' value");
            os.flush();
            os.close();
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
            System.err.println("Visit "+filePath+" for updating "+key+" value error");
            log.error("Visit "+filePath+" for updating "+key+" value error."+e);
        }
        finally {
            try {
                if (null != is)
                    is.close();
                if (null != os)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e);
            }

        }
    }

    public static void main(String[] args) throws Exception {
        String taskFile="task.properties";
        PropertiesUtil pro2= new PropertiesUtil(taskFile);
        //pro2.writeProperty("taskId","777777777777777777777");

        System.out.println(pro2.readProperty("taskId"));

    }


}

其中遇到问题(下面这两种读取的都是class(编译后的目录)下面的文件)

String filePath = PropertiesUtil.class.getClassLoader().getResource(propertiesName).getPath();
String filePath = PropertiesUtil.class.getResource("/"+propertiesName).getPath();

指定resource路径才能直接写到src/main/resources目录下的源文件。

参考:

https://blog.csdn.net/Dancer_AI/article/details/110450524

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁儿测试开发

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值