Java 项目读取 resource 资源文件路径问题
问题
正常在 Java 工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径即相对当前类的路径。
本地读取资源文件
采用文件(File方式进行读取)
public void test1() throws IOException {
File file = new File("src/main/resources/database.properties");
byte[] bytes = new byte[1024];
StringBuffer sb = new StringBuffer();
int byteread = 0;
FileInputStream fis = new FileInputStream(file);
while ((byteread = fis.read(bytes)) != -1){
String s = new String(bytes, 0, byteread);
sb.append(s);
}
System.out.println(sb);
}
服务器读取资源
方式一
采用流(Stream)的方式读取,并通过JDK中Properties类加载,可以方便的获取到配置文件中的信息
public void test3() throws IOException {
// this.getClass() = test.class
//采用ClassLoader对象去加载资源文件
InputStream in1 = this.getClass().getClassLoader().getResourceAsStream("database.properties");
//采用Class对象去加载
// InputStream in3 = this.getClass().getResourceAsStream("/resources/database.properties");
Properties properties = new Properties();
properties.load(in1);
String driver = properties.getProperty("driver");
System.out.println(driver);
}
采用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>
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: