正常在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
2
然后在程序中可以使用 @Value进行获取properties文件中的属性值,如下:
1 @Value("${xxxt.server}")2 private static String serverUrl;
方式三:采用Spring配置
也可以在Spring配置文件中读取属性值,赋予类成员变量
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans5 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
6
7 8
9
10
11
12
13
14
15
举例说明,服务类:
1 packagecom.springtest.service;2
3 public classServiceImpl {4
5 privateString serverUrl;6
7 publicString getServerUrl() {8 returnserverUrl;9 }10
11 public voidsetServerUrl(String serverUrl) {12 this.serverUrl =serverUrl;13 }14
15 public voidsayHello(){16 System.out.println(serverUrl);17 }18 }
配置文件:
server=123.23.43.23
测试:
1 public classServiceTest {2
3 public static voidmain(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
参考: