zoukankan      html  css  js  c++  java
  • ClassPathResource读取classpath路径下的文件内容

    在做项目的过程中,需要将一些参数写入properties文件的配置中,如何读取到properties的文件内容呢,我用到了spring core提供的类org.springframework.core.io.ClassPathResource,通过这个类,可以读取到指定classpath下路径的文件内容。

    用来读取properties配置的工具类如下所示:

    package com.x.certificate.properties;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Properties;
    
    import org.springframework.core.io.ClassPathResource;
    
    /** 
     * 读取properties文件的配置
     * @author xuhaojin
     * @version [版本号, 2020年3月23日]
     */
    public class PropertiesReader {
    
        public static String getConfig(String pathInDemo, String key) throws IOException {
            return getProperties(pathInDemo).getProperty(key);
        }
    
        public static Properties getProperties(String pathInDemo) throws IOException {
            Properties properties = new Properties();
    
            ClassPathResource classPathResource = new ClassPathResource(pathInDemo);
    
            File file = classPathResource.getFile();
    
            BufferedReader bufferedReader = null;
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                properties.load(bufferedReader);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return properties;
        }
    
        public static void main(String[] args) throws IOException {
            System.out.println("libreoffice.path=" + getConfig("config\certificate.properties", "libreoffice.path"));
            System.out.println(
                    "certificate.image.suffix=" + getConfig("config\certificate.properties", "certificate.image.suffix"));
        }
    
    }

    其中下面这两行代码获取到配置文件:

           ClassPathResource classPathResource = new ClassPathResource(pathInDemo);
           File file = classPathResource.getFile()

    配置文件的实际路径在src/test/resources的config文件夹下:

  • 相关阅读:
    新建安卓项目后,manifest.xml中会出现大段的黄色警告
    TextView设置setCompoundDrawables不生效解决办法
    数据结构->队列->顺序循环队列ADT代码
    数据结构->栈->顺序栈ADT代码
    JAVA环境变量的配置
    计算机科学的范围-----18.12.08
    字符串复制
    扔鸡蛋问题和找零钱问题
    动态规划
    最小二乘法
  • 原文地址:https://www.cnblogs.com/xhj123/p/12562226.html
Copyright © 2011-2022 走看看