java 资源文件路径问题

在JAVA项目中读取资源文件经常会遇到路径的问题
最近总结了一下几种路径的获取方法

一、CLASSPATH 路径
1.说明
     对于普通应用程序来说此路径  项目名/bin/classes
     对于WEB程序来说是在          WEB-INF/classes
2.读取方法(SpringTest是项目下的随意一个类)
     1)  path= SpringTest.class.getResource("").getPath(); //类所在的目录
     2)  path= SpringTest.class.getClassLoader().getResource("").getPath();//classes目录
     3)  path= SpringTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();//classes目录

spring中的配置
<!-- 属性文件读入 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:config/*.properties</value>
			</list>
		</property>
	</bean>


二、应用程序所在路径user.dir

补充说明:应用程序所在路径其实是应用程序启动时的路径
弱弱的说,就是你在项目中new File("abc.txt") abc.txt存放的路径

对于tomcat来说 user.dir的值和启动时的路径有直接的关系
如果你在bin目录下启动, 那么user.dir就是tomcat/bin
如果在tomcat目录下启动 ./bin/startup.sh启动,则user.dir是tomcat
最好的办法是 在catalina.sh文件中 JAVA_OPTS增加-Duser.dir=tomcat(你期望的路径)
这样无论你在哪个目录下启动tomcat user.dir的值都是一样的

1.说明
     对于普通应用程序来说此路径  项目所在目录
     对于WEB程序来说是在         tomcat所在目录

2.获取方法
     1) path= System.getProperty("user.dir"); // 工程路径(未在web项目下测试)
     2) path= new UrlResource(new URL("file:")).getFile().getAbsoluteFile().getAbsolutePath();


spring中的配置
<!-- 属性文件读入 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>file:config/*.properties</value>
			</list>
		</property>
	</bean>


当然肯定还有其它方法,有兴趣的朋友可以帮我补充一下.

原创: http://yxjajl.iteye.com/blog/2321787
    

猜你喜欢

转载自yxjajl.iteye.com/blog/2321787