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文件夾下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM