通过key,获取.properties文件中的值

南翔技校毕业后 / 2024-10-13 / 原文

news.properties文件:

#title
titleNode=/body/div[5]/div[2]/div[3]/h1/span[1]
#theYear
theYearNode=/body/div[5]/div[2]/div[1]/span[1]/em
#monthAndDay
monthAndDayNode=/body/div[5]/div[2]/div[1]/span[2]
#theTime
theTimeNode=/body/div[5]/div[2]/div[1]/span[3]
#source
sourceNode=/body/div[5]/div[2]/div[2]
#content
contentNode=//*[@id=\"detail\"]
#author
authorNode=//*[@id=\"articleEdit\"]/span[2]
 
#source的正则表达式
sourceRegex=来源:(.*)
 
 
#数据库连接
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://10.10.50.160:3306/learningspider?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
username=root
password=abc123456#

代码实现

/**
 * @author jiangl
 * @ClassName loadProperty.java
 * @Description 加载news.properties配置文件
 * @createTime 2021年01月11日 21:24
 */
public class loadProperty
{
    //定义properties配置文件路径
    final static String filePath = "src/main/resources/news.properties";
 
    /*
    通过key,获取properties的值,已经处理中文乱码
     */
    public static String load(String key) throws IOException
    {
        Properties properties = new Properties();
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "GBK");
        BufferedReader read = new BufferedReader(isr);
        properties.load(read);
        return properties.getProperty(key);
 
    }
 
}

测试

    @Test
    public void test() throws IOException
    {
        System.out.println(load("sourceRegex"));
 
    }