读取classpath下properties文件,将属性写入到外部文件夹properties文件属性中


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * @author
 * @site
 * @company
 * @create 2023-01-16 15:14
 */
@Configuration
public class ScheduleConfig {

    @Value("${mes.home}")
    public String cbs;

    @Bean()
// /@Scope(value = "prototype") 多例bean,修改yml,会立即生效
    public Properties loadProperties() throws IOException {

        File file = new File(cbs + File.separator + "schedule.properties");

        if(!file.exists()){
            file.createNewFile();

            // Properties格式文件的写入 file
            try (BufferedInputStream bis = new BufferedInputStream( getClass().getClassLoader()
                    .getResourceAsStream("schedule.properties"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {

                Properties props = new Properties();

                props.load(bis); // 将“输入流”加载至Properties集合对象中

                props.store(bos, "定时任务");

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        Properties props = new Properties();

        try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file))) {

            props.load(bis);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return props;
    }

}

  其中 @Value("${mes.home}") 中 mes,home 为属性文件中配置本地路径

      schedule.properties 为resource下配置文件,也是读取文件,本文主要目的将resource 下的schdule.properties 属性写到到外部配置   ${mes.home}/schedule.properties

 

参考文献  https://www.bbsmax.com/A/6pdDl0DRdw/ 

posted @ 2023-01-17 14:51  职业吃井人  阅读(77)  评论(0编辑  收藏  举报