0
点赞
收藏
分享

微信扫一扫

Java 路径问题

王传学 2022-04-07 阅读 120
java

Java的路径问题,非常难搞。本文讲解Java路径问题。

一、Java路径

Java中使用的路径,分为两种:绝对路径和相对路径。具体而言,又分为四种:

1.  URI 形式的绝对路径

2. 本地系统的绝对路径

3. 相对于classpath的相对路径

4. 相对于当前用户目录的相对路径

二、相对路径最佳实践

示例基于Spring boot项目。

1. 推荐使用相对于当前classpath的相对路径

2. 得到classpath和当前类的绝对路径的一些方法

下面是一些得到classpath和当前类的绝对路径的一些方法。

(1)得到当前类FileTest.class文件的URI目录。不包括自己文件类名!

(2)得到当前的classpath的绝对URI路径。

(3)获取项目路径

(4)获取磁盘根目录

(5)获取./路径

// 路径为当前相对目录./时
File fileCurrent = new File("./");
// 返回结果:E:\yangyang-ba\ETC\receive\.
System.out.println(fileCurrent.getAbsoluteFile());

三、Web应用程序中资源的寻址

四、通用的相对路径解决办法

Java中各种相对路径非常多,不容易使用,非常容易出错。因此,我编写了一个便利方法,帮助更容易的解决相对路径问题。

Web应用程序中使用JavaSE运行的资源寻址问题

在JavaSE程序中,我们一般使用classpath来作为存放资源的目的地。但是,在Web应用程序中,我们一般使用classpath外面的WEB-INF及其子目录作为资源文件的存放地。

在Web应用程序中,我们一般通过ServletContext.getRealPath("/")方法得到Web应用程序的根目录的绝对路径。这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。

Web应用程序,可以作为Web应用程序进行发布和运行。但是,我们也常常会以JavaSE的方式来运行Web应用程序的某个类的main方法。或者,使用JUnit测试。这都需要使用JavaSE的方式来运行。

这样,我们就无法使用ServletContext.getRealPath("/")方法得到Web应用程序的根目录的绝对路径。而JDK提供的ClassLoader类,它的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。

读取属性文件常用到的ResourceBundle类的getBundle(String path)也是如此。它们都只能使用相对路径来读取classpath下的资源,无法定位到classpath外面的资源

通用的相对路径解决办法

面对这个问题,我决定编写一个助手类ClassLoaderUtil,提供一个便利方法[public static URL getExtendResource(String relativePath)]。在Web应用程序等一切Java程序中,需要定位classpath外的资源时,都使用这个助手类的便利方法,而不使用Web应用程序特有的ServletContext.getRealPath("/")方法来定位资源。

利用classpath的绝对路径,定位所有资源

这个便利方法的实现原理,就是“利用classpath的绝对路径,定位所有资源”。
ClassLoader类的getResource("")方法能够得到当前classpath的绝对路径,这是所有Java程序都拥有的能力,具有最大的适应性!

而目前的JDK提供的ClassLoader类的getResource(String 相对路径)方法,只能接受一般的相对路径。这样,使用ClassLoader类的getResource(String 相对路径)方法就只能定位到classpath下的资源。

如果,它能够接受“…/”这样的参数,允许我们用相对路径来定位classpath外面的资源,那么我们就可以定位位置的资源!

当然,我无法修改ClassLoader类的这个方法,于是,我编写了一个助手类ClassLoaderUtil类,提供了[public static URL getExtendResource(String relativePath)]这个方法。它能够接受带有“…/”符号的相对路径,实现了自由寻找资源的功能。

通过相对classpath路径实现自由寻找资源的助手类的源代码:

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;

/**
*用来加载类
*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
*/
public static 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());

}

}

总结

1、尽量不要使用相对于

System.getProperty("user.dir");

当前用户目录的相对路径。这是一颗定时炸弹,随时可能要你的命。

2、尽量使用URI形式的绝对路径资源。它可以很容易的转变为URI,URL,File对象。

3、尽量使用相对classpath的相对路径。不要使用绝对路径。使用上面ClassLoaderUtil类

public static URL getExtendResource(String relativePath);

方法已经能够使用相对于classpath的相对路径定位所有位置的资源。

4、绝对不要使用硬编码的绝对路径。因为,我们完全可以使用ClassLoader类的getResource("")方法得到当前classpath的绝对路径。

使用硬编码的绝对路径是完全没有必要的!它一定会让你死的很难看!程序将无法移植!

如果你一定要指定一个绝对路径,那么使用配置文件,也比硬编码要好得多!当然,我还是推荐你使用程序得到classpath的绝对路径来拼资源的绝对路径!

举报

相关推荐

0 条评论