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执行:

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

相关推荐
qq_124987075336 分钟前
基于springboot的疾病预防系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
麦烤楽鸡翅37 分钟前
简单迭代法求单根的近似值
java·c++·python·数据分析·c·数值分析
火星数据-Tina1 小时前
低成本搭建体育数据中台:一套 API 如何同时支撑比分网与 App?
java·前端·websocket
lcu1111 小时前
Java 学习38:ArrayList 类
java
q***2511 小时前
Spring Boot 集成 Kettle
java·spring boot·后端
筱顾大牛1 小时前
IDEA使用Gitee来创建远程仓库
java·gitee·intellij-idea
懂得节能嘛.2 小时前
【SDK开发实践】从Java编码到阿里云制品仓库部署
java·阿里云·maven
空空kkk2 小时前
SpringMVC——异常
java·前端·javascript
重整旗鼓~2 小时前
1.大模型使用
java·语言模型·langchain
sino爱学习3 小时前
FastUtil 高性能集合最佳实践:让你的 Java 程序真正“快”起来
java·后端