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

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

相关推荐
Drifter_yh43 分钟前
【黑马点评】Redisson 分布式锁核心原理剖析
java·数据库·redis·分布式·spring·缓存
莫寒清2 小时前
Spring MVC:@RequestParam 注解详解
java·spring·mvc
没有医保李先生3 小时前
字节对齐的总结
java·开发语言
甲枫叶4 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
六件套是我4 小时前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
LYS_06185 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
forestsea5 小时前
Spring Cloud Alibaba 2025.1.0.0 正式发布:拥抱 Spring Boot 4.0 与 Java 21+ 的新时代
java·spring boot·后端
IT枫斗者5 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
forestsea5 小时前
Spring Boot 4.0 + JDK 25 + GraalVM:下一代云原生Java应用架构
java·spring boot·云原生