maven工程中读取resources中的资源文件

maven工程的代码布局如下:在resources下面有一个资源文件test.properties,现在的目标要在Java代码中读取该资源文件中的内容。

test.properties资源文件的内容如下:

Java代码如下:

复制代码
package com.thb;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;

import java.util.Map.Entry;

public class Demo {
    
    public static void main(String[] args) {

        String fileName = "/test.properties";
        URL url = Demo.class.getResource(fileName);  
        String path = url.getPath();

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
            Properties pro = new Properties();
            pro.load(in);
            for (Entry<Object, Object>entry : pro.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

1)在cmd下运行mvn compile进行编译:

2)运行mvn exec:java -Dexec.mainClass=com.thb.Demo执行:

从输出可以看出,得到了正确的结果。

相关推荐
RainbowSea14 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea15 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑19 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613519 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊20 小时前
Java学习第22天 - 云原生与容器化
java
渣哥1 天前
原来 Java 里线程安全集合有这么多种
java
间彧1 天前
Spring Boot集成Spring Security完整指南
java
间彧1 天前
Spring Secutiy基本原理及工作流程
java
zjjuejin1 天前
Maven项目的核心蓝图:POM文件
前端·maven
Java水解1 天前
JAVA经典面试题附答案(持续更新版)
java·后端·面试