Java工程读取resources中资源文件路径问题

时间:2023-03-09 17:13:12
Java工程读取resources中资源文件路径问题

正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径,即相对于当前类的路径。在本地工程和服务器中读取文件的方式有所不同,以下图配置文件为例。

Java工程读取resources中资源文件路径问题

本地读取资源文件

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

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

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

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

方式一:采用流+Properties

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

Java工程读取resources中资源文件路径问题

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

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

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

方式二:采用Spring注解

如果工程中使用Spring,可以通过注解的方式获取配置信息,但需要将配置文件放到Spring配置文件中扫描后,才能将配置信息放入上下文。

 <context:component-scan base-package="com.xxxx.service"/>
<context:property-placeholder location="classpath:properties/xxx.properties" ignore-unresolvable="true"/>

然后在程序中可以使用 @Value进行获取properties文件中的属性值,如下:

 @Value("${xxxt.server}")
private static String serverUrl;

方式三:采用Spring配置

也可以在Spring配置文件中读取属性值,赋予类成员变量

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/xxx.properties"/>
</bean> <bean id="service" class="com.xxxx.service.ServiceImpl">
<property name="serverUrl" value="${xxxt.server}" />
</bean> </beans>

举例说明,服务类:

 package com.springtest.service;

 public class ServiceImpl {

     private String serverUrl;

     public String getServerUrl() {
return serverUrl;
} public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
} public void sayHello(){
System.out.println(serverUrl);
}
}

配置文件:

server=123.23.43.23

测试:

 public class ServiceTest {

     public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring.xml");
ServiceImpl s = ctx.getBean("service", ServiceImpl.class);
s.sayHello();
} }

输出:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
123.23.43.23

参考:

Resource from src/main/resources not found after building with maven

[Java] 在 jar 文件中读取 resources 目录下的文件