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

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

相关推荐
极光代码工作室1 小时前
基于SpringBoot的在线博客系统
java·springboot·web开发·后端开发
我是唐青枫1 小时前
Java Spring Security 实战详解:从登录认证到 JWT 权限控制
java·spring
ihuyigui2 小时前
海外签收通知短信接口
android·java·开发语言·前端·数据库·后端
海棠Flower未眠2 小时前
SpringBoot 消息死信队列(荣耀典藏版)
java·数据库·spring boot
暖和_白开水2 小时前
数据分析agent (七):contextvars 模块上下文request_id
java·前端·数据分析
weixin_727535623 小时前
MinIO大文件上传深度拆解:从原理到生产落地的完整指南
java·中间件
摇滚侠4 小时前
Java 全栈开发实战教程 课程笔记 34-36
java·笔记
芝士熊爱编程4 小时前
创建型模式-单例模式
java·单例模式·设计模式
大模型码小白4 小时前
Spring AI 框架实战:Java 后端集成大模型的架构设计与工程落地
java·人工智能·python·spring
weixin_BYSJ19874 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php