关于怎么读取Maven项目resource目录下面的文件

项目中同事问的问题,本来是直接利用绝对路径读取的。利用System.getProperty(“user.dir”)‘’这个方法进行获取项目的路径,但是他要求用相对路径获取,就试了下一下的方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {
        InputStream in = ClassLoader.getSystemResourceAsStream("spring-mvc.xml");
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line;
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
        br.close();
        in.close();
    }
}

亲测可用!并且百度到另以文章:http://regedit-123.iteye.com/blog/1126130

使用ClassLoader.getSystemResourceAsStream(“/mypropertiestest.properties”)和Thread.currentThread().getContextClassLoader().getResourceAsStream(“/mypropertiestest.properties”)读取src下的属性文件,通过测试,在windows和Linux下的tomcat和apusic都能成功。

猜你喜欢

转载自blog.csdn.net/ls0111/article/details/77059913