总结自很多文章与书籍
尤其是: 强烈推荐
1.在IDE中获取路径
File f = new File("config.txt");
在IDE中如果是这样 那么 f.getAbsolutePath() 这个方法返回的绝对路径是这个项目的根目录中的config.txt文件
在Linux非IDE中,返回的值当前路径下的config.txt文件
File f = new File("/config.txt");
在windows下返回的是c盘的config.txt文件,在Linux下返回的是root目录下的config.txt
原理:
jvm 通过System.getProperty("user.dir") 的对应路径 和上面我们写在File中的字符串拼接得到绝对地址,注意前面不要加/
注意
对于一般的项目 这个user.dir是项目的根路径
但是对于服务器上的文件 这个可能就不是了
所以不要用这个来找文件。
试验:
user.dir的值会根据生成的.class文件所在目录的不同而变化。
2.在classpath下读取路径
1,FileTest.class.getResource("")
得到的是当前类FileTest.class文件的URI目录。不包括自己!(包含这个.class文件所在的bin目录和所有层级的包目录,不包括自己的文件名)
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
2 ,FileTest.class.getResource("/")
得到的是当前的classpath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
3 ,Thread.currentThread().getContextClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
4 ,FileTest.class.getClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
5 ,ClassLoader.getSystemResource("")
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
推荐使用Thread.currentThread().getContextClassLoader().getResource("")来得到当前的classpath的绝对路径的URI表示法。
代码:
由此可见 通过File这种形式获得的路径都是project的根目录
而用getResource这种形式获得的路径,是项目编译之后的classpath目录 也就是bin目录
获取文件路径主要用于哪里:
主要用于对配置文件等.class文件之外的资源进行读取,读取之前肯定要定位这些文件的位置
用绝对路径肯定是不行,因为一旦你更换了路径或者移植到别的电脑上,就无法找到该资源
所以用相对路径。
就是这个资源相对于classpath也就是bin目录的路径
在javase程序中,一般这些资源文件是和classpath目录,也就是bin目录放在一起的,所以直接用class.getResource 方法获取路径就行
但是在web程序中,这些资源很可能不存放在classpath目录下,而是存在和classpath目录平行的WEB—INF等目录下
此时用原有的方法只能定位到classpath目录,而用绝对路径又不行,所以就要重新写方法来找到资源的路径
之所以不能定位到classpath平行的目录,是因为getResource方法中不可以传入../这样的访问上级目录的字符串
所以 想要解决这个问题,只需要模拟一下../所做的操作即可
总结 :
使用基于classpath路径的方法,千万不要使用基于user.dir的方法,也不要使用绝对路径
以下代码还没有看:勿忘
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*@author沈东良shendl_s@hotmail.com
*Nov29,2006 10:34:34AM
*用来加载类,classpath下的资源文件,属性文件等。
*getExtendResource(StringrelativePath)方法,可以使用../符号来加载classpath外部的资源。
*/
publicclass ClassLoaderUtil {
privatestatic Log log=LogFactory.getLog(ClassLoaderUtil.class);
/**
*Thread.currentThread().getContextClassLoader().getResource("")
*/
/**
*加载Java类。 使用全限定类名
*@paramclassName
*@return
*/
publicstatic Class loadClass(String className) {
try {
return getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
thrownew RuntimeException("class not found '"+className+"'", e);
}
}
/**
*得到类加载器
*@return
*/
publicstatic ClassLoader getClassLoader() {
return ClassLoaderUtil.class.getClassLoader();
}
/**
*提供相对于classpath的资源路径,返回文件的输入流
*@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
*@return 文件输入流
*@throwsIOException
*@throwsMalformedURLException
*/
publicstatic InputStream getStream(String relativePath) throws MalformedURLException, IOException {
if(!relativePath.contains("../")){
return getClassLoader().getResourceAsStream(relativePath);
}else{
return ClassLoaderUtil.getStreamByExtendResource(relativePath);
}
}
/**
*
*@paramurl
*@return
*@throwsIOException
*/
publicstatic InputStream getStream(URL url) throws IOException{
if(url!=null){
return url.openStream();
}else{
returnnull;
}
}
/**
*
*@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
*@return
*@throwsMalformedURLException
*@throwsIOException
*/
publicstatic InputStream getStreamByExtendResource(String relativePath) throws MalformedURLException, IOException{
return ClassLoaderUtil.getStream(ClassLoaderUtil.getExtendResource(relativePath));
}
/**
*提供相对于classpath的资源路径,返回属性对象,它是一个散列表
*@paramresource
*@return
*/
publicstatic Properties getProperties(String resource) {
Properties properties = new Properties();
try {
properties.load(getStream(resource));
} catch (IOException e) {
thrownew RuntimeException("couldn't load properties file '"+resource+"'", e);
}
return properties;
}
/**
*得到本Class所在的ClassLoader的Classpat的绝对路径。
*URL形式的
*@return
*/
publicstatic String getAbsolutePathOfClassLoaderClassPath(){
ClassLoaderUtil.log.info(ClassLoaderUtil.getClassLoader().getResource("").toString());
return ClassLoaderUtil.getClassLoader().getResource("").toString();
}
/**
*
*@paramrelativePath 必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
*@return资源的绝对URL
*@throwsMalformedURLException
*/
publicstatic URL getExtendResource(String relativePath) throws MalformedURLException{
ClassLoaderUtil.log.info("传入的相对路径:"+relativePath) ;
//ClassLoaderUtil.log.info(Integer.valueOf(relativePath.indexOf("../"))) ;
if(!relativePath.contains("../")){
return ClassLoaderUtil.getResource(relativePath);
}
String classPathAbsolutePath=ClassLoaderUtil.getAbsolutePathOfClassLoaderClassPath();
if(relativePath.substring(0, 1).equals("/")){
relativePath=relativePath.substring(1);
}
ClassLoaderUtil.log.info(Integer.valueOf(relativePath.lastIndexOf("../"))) ;
String wildcardString=relativePath.substring(0,relativePath.lastIndexOf("../")+3);
relativePath=relativePath.substring(relativePath.lastIndexOf("../")+3);
int containSum=ClassLoaderUtil.containSum(wildcardString, "../");
classPathAbsolutePath= ClassLoaderUtil.cutLastString(classPathAbsolutePath, "/", containSum);
String resourceAbsolutePath=classPathAbsolutePath+relativePath;
ClassLoaderUtil.log.info("绝对路径:"+resourceAbsolutePath) ;
URL resourceAbsoluteURL=new URL(resourceAbsolutePath);
return resourceAbsoluteURL;
}
/**
*
*@paramsource
*@paramdest
*@return
*/
privatestaticint containSum(String source,String dest){
int containSum=0;
int destLength=dest.length();
while(source.contains(dest)){
containSum=containSum+1;
source=source.substring(destLength);
}
return containSum;
}
/**
*
*@paramsource
*@paramdest
*@paramnum
*@return
*/
privatestatic String cutLastString(String source,String dest,int num){
// String cutSource=null;
for(int i=0;i<num;i++){
source=source.substring(0, source.lastIndexOf(dest, source.length()-2)+1);
}
return source;
}
/**
*
*@paramresource
*@return
*/
publicstatic URL getResource(String resource){
ClassLoaderUtil.log.info("传入的相对于classpath的路径:"+resource) ;
return ClassLoaderUtil.getClassLoader().getResource(resource);
}
/**
*@paramargs
*@throwsMalformedURLException
*/
publicstaticvoid main(String[] args) throws MalformedURLException {
//ClassLoaderUtil.getExtendResource("../spring/dao.xml");
//ClassLoaderUtil.getExtendResource("../../../src/log4j.properties");
ClassLoaderUtil.getExtendResource("log4j.properties");
System.out.println(ClassLoaderUtil.getClassLoader().getResource("log4j.properties").toString());
}
}