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

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

相关推荐
lulu121654407836 分钟前
Claude Code Harness架构技术深度解析:生产级AI Agent工程化实践
java·人工智能·python·ai编程
阿里加多38 分钟前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
一 乐43 分钟前
物流信息管理|基于springboot + vue物流信息管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·物流信息管理系统
2301_792674861 小时前
java学习day29(juc)
java·开发语言·学习
希望永不加班2 小时前
SpringBoot 自动配置类加载顺序与优先级
java·spring boot·后端·spring·mybatis
纸鸢|2 小时前
从“一锤子买卖“到“持续价值共生“:物联网软件产品如何做到“叫好又叫座“
java·物联网·struts
云霄IT3 小时前
安卓开发之java转dex再转smali
android·java·python
用户6688599847663 小时前
BCrypt密码加密
java
赵药师3 小时前
多进程-生产者消费者C++实现
java·开发语言·jvm
Flittly3 小时前
【SpringAIAlibaba新手村系列】(16)调用百度 MCP 服务
java·笔记·spring·ai·springboot