正常在Java工程中讀取某路徑下的文件時,可以采用絕對路徑和相對路徑,絕對路徑沒什么好說的,相對路徑,即相對於當前類的路徑。在本地工程和服務器中讀取文件的方式有所不同,以下圖配置文件為例。
本地讀取資源文件
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類加載,可以方便的獲取到配置文件中的信息,如下:
1 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配置文件中掃描后,才能將配置信息放入上下文。
1 <context:component-scan base-package="com.xxxx.service"/> 2 <context:property-placeholder location="classpath:properties/xxx.properties" ignore-unresolvable="true"/>
然后在程序中可以使用 @Value進行獲取properties文件中的屬性值,如下:
1 @Value("${xxxt.server}") 2 private static String serverUrl;
方式三:采用Spring配置
也可以在Spring配置文件中讀取屬性值,賦予類成員變量
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> 6 7 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 8 <property name="location" value="classpath:properties/xxx.properties"/> 9 </bean> 10 11 <bean id="service" class="com.xxxx.service.ServiceImpl"> 12 <property name="serverUrl" value="${xxxt.server}" /> 13 </bean> 14 15 </beans>
舉例說明,服務類:
1 package com.springtest.service; 2 3 public class ServiceImpl { 4 5 private String serverUrl; 6 7 public String getServerUrl() { 8 return serverUrl; 9 } 10 11 public void setServerUrl(String serverUrl) { 12 this.serverUrl = serverUrl; 13 } 14 15 public void sayHello(){ 16 System.out.println(serverUrl); 17 } 18 }
配置文件:
server=123.23.43.23
測試:
1 public class ServiceTest { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring.xml"); 6 ServiceImpl s = ctx.getBean("service", ServiceImpl.class); 7 s.sayHello(); 8 } 9 10 }
輸出:
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