java读取配置文件工具类

18 篇文章 0 订阅

如何读取下方配置文件并且向其中传入参数:

在这里插入图片描述
执行成功的截图
在这里插入图片描述

使用改工具类的方法:

public static void main(String[] args) {
        PropertyUtil properties=new PropertyUtil();
        Map<String,String> map=new HashMap<>();
        map.put("tableName","user");
        map.put("id","1001");
        map.put("name","张三");
        String sql = properties.get("config.properties", "sql",map);
        System.out.println(sql);
        }

执行截图

在这里插入图片描述

工具类:

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

/**
 * @Author mabo
 * @Description   用于读取配置文件的工具类
 */

public class PropertyUtil {
    private  static LogUtil log=new LogUtil();
    //设置配置文件的基本路径
    private static String path ="properties/";
    /**
 * @Author mabo
 * @Description   获取配置文件对象
 */
    public Properties getProperties(String propertiesName) {
        Properties props = new Properties();
        Resource resource = new ClassPathResource(path+propertiesName);
        if(resource!=null){
            try {
                InputStream is = resource.getInputStream();
                BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                props.load(bf);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(propertiesName+"配置文件读取失败");
            }
        }
        else log.error(propertiesName+"配置文件不存在");
        return  props;
    }

    /**
     * @Author mabo
     * @Description   指定配置文件名,和key,获取value
     */
    public String get(String propertyFileName,String key){
        PropertyUtil propertyUtil=new PropertyUtil();
        Properties properties = propertyUtil.getProperties(propertyFileName);
        String value=null;
        value =  properties.getProperty(key);
        if (value==null){
            log.error("配置文件"+propertyFileName+"获取-------:"+key+"失败");
        }
        return  value;
    }

    /**
     * @Author mabo
     * @Description  根据配置文件传入的map组装数据
     */
    public String get(String propertyFileName, String key, Map<String, String> map){
        try {
            String string = get(propertyFileName, key);
            for(int i = 0;  i < string.length(); i ++) {
                int flag = string.indexOf("$",i);
                int left = string.indexOf("{",i);
                int right = string.indexOf("}", i);
                if(flag < 0||left < 0||right < 0) {
                    log.error(propertyFileName+"配置文件读取错误");
                    return null;
                }
                else {
                    String value = string.substring(left+1, right);
                    String s = map.get(value);
                    string=  string.replace("${"+value+"}",s);
                }
                i = right;
            }
            return string;
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error(propertyFileName+"配置文件读取错误");
            return null;
        }
    }

}

附加日志工具类

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Author mabo
 * @Description   日志记录工具类
 */

public class LogUtil {
    private static String  path = LogUtil.class.getResource("").getPath();
    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat ymdHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static  String logPosition=System.getProperty("user.dir");
    /**
     * @Author mabo
     * @Description   用于接受消息
     */
    public void message(String info,int flag){
        String messageType="";
        if(flag==1){
            messageType="信息|";
        }
        else if(flag==0){
            messageType="错误-";
        }
        Date date=new Date();
        StringBuilder msg=new StringBuilder();
        msg.append(logPosition);
        msg.append("\\log\\");
        msg.append(ymd.format(date));
        msg.append(".txt");
        File file = new File(msg.toString());
        if (!file.exists()) {
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        OutputStreamWriter write = null;
        try {
            write = new OutputStreamWriter(new FileOutputStream(file,true),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedWriter writer=new BufferedWriter(write);
        //写入信息
        try {
            writer.append(messageType+ymdHMS.format(date)+"=:"+info);
            System.out.println(messageType+ymdHMS.format(date)+"=:"+info);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author mabo
     * @Description   信息日志
     */
    public void info(String info){
        LogUtil logUtil=new LogUtil();
        logUtil.message(info,1);
    }
    /**
     * @Author mabo
     * @Description   错误日志
     */
    public void error(String error) {
        LogUtil logUtil=new LogUtil();
        logUtil.message(error,0);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Java配置文件分段读取工具类,可以将配置文件按照section分段读取,每个section中的键值对以Map的形式存储: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ConfigParser { private String filename; private Map<String, Map<String, String>> sections; public ConfigParser(String filename) throws IOException { this.filename = filename; this.sections = new HashMap<>(); parse(); } public String get(String section, String option) { Map<String, String> options = sections.get(section); if (options != null) { return options.get(option); } return null; } public void set(String section, String option, String value) { Map<String, String> options = sections.computeIfAbsent(section, k -> new HashMap<>()); options.put(option, value); } private void parse() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String line; String section = null; Map<String, String> options = new HashMap<>(); while ((line = br.readLine()) != null) { line = line.trim(); if (line.matches("\\[.*\\]")) { if (section != null) { sections.put(section, options); } section = line.substring(1, line.length() - 1); options = new HashMap<>(); } else if (line.matches(".*=.*")) { String[] parts = line.split("=", 2); String option = parts[0].trim(); String value = parts[1].trim(); options.put(option, value); } } if (section != null) { sections.put(section, options); } } } } ``` 使用示例: ```java public static void main(String[] args) throws IOException { ConfigParser config = new ConfigParser("config.ini"); String value = config.get("section1", "option1"); System.out.println(value); config.set("section2", "option2", "value2"); // ... } ``` 其中,`config.ini`配置文件的格式如下: ``` [section1] option1 = value1 option2 = value2 [section2] option3 = value3 option4 = value4 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值