java 如何读取src根目录下的属性文件

在java项目中,如何获取src根目录下的属性文件/资源文件呢?

有如下三种方式:

方式一:

InputStream in = Test.class   
        .getResourceAsStream("/env.properties");  
URL url = Test.class.getResource("<span style="color: #000000;">/</span>env.properties")  ;  

 说明:env.properties文件在src的根目录下,文件名前有斜杠

方式二:

InputStream in = Test.class.getClassLoader()    
      .getResourceAsStream("env.properties");  
URL url = Test.class.getClassLoader().getResource("env.properties")  ;  

方式三:

InputStream in = Thread.currentThread().getContextClassLoader()  
                .getResourceAsStream("ExcelModeMappingl.xml");  

 示例:

private Properties readConfig(){
InputStream in = this.getClass().getResourceAsStream("/config.properties");
// String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
// int lastIndex = path.lastIndexOf(File.separator) + 1;
// path = path.substring(0, lastIndex);
// File configFile = new File(path + "configration.properties");
// InputStream in = null;
// try
// {
// in = new FileInputStream(configFile);
// }
// catch (FileNotFoundException e)
// {
// e.printStackTrace();
// }

Properties props = new Properties();
InputStreamReader inputStreamReader = null;
try
{
inputStreamReader = new InputStreamReader(in, "UTF-8");
props.load(inputStreamReader);
}
catch (Exception e)
{
e.printStackTrace();
}
return props;
}
config.properties在src/main/resources目录下
注释掉的部分是读取jar包平级目录下的配置文件。有时需要把配置文件放在jar包外面方便配置,因此需要读取jar包外的配置文件。

本地读取资源文件

java类中需要读取properties中的配置文件,可以采用文件(File)方式进行读取:

1 File file = new File("src/main/resources/properties/basecom.properties");
2 InputStream in = new FileInputStream(file);

当在eclipse中运行(不部署到服务器上),可以读取到文件。

服务器(Tomcat)读取资源文件

采用流+Properties

当工程部署到Tomcat中时,按照上边方式,则会出现找不到该文件路径的异常。经搜索资料知道,Java工程打包部署到Tomcat中时,properties的路径变到顶层(classes下),这是由Maven工程结构决定的。由Maven构建的web工程,主代码放在src/main/java路径下,资源放在src/main/resources路径下,当构建为war包的时候,会将主代码和资源文件放置classes文件夹下:

并且,此时读取文件需要采用流(stream)的方式读取,并通过JDK中Properties类加载,可以方便的获取到配置文件中的信息,如下:

 InputStream in = this.getClass().getResourceAsStream("/properties/basecom.properties");
Properties properties = new Properties();
properties.load(in);
properties.getProperty("property_name");

 其中properties前的斜杠,相对于调用类,共同的顶层路径。

原文地址:https://www.cnblogs.com/endtel/p/11750850.html