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执行:
在这里插入图片描述
从输出可以看出,得到了正确的结果。

猜你喜欢

转载自blog.csdn.net/panghuangang/article/details/135016451