java Web 项目获得文件的绝对路径

文件在项目中的路径

maven 项目

maven project

如上图,maven项目的资源文件一般是放在src/main/resources目录下。

一般的web项目

web project

对于一般的web项目的资源文件一般是放在WEB-INF目录下。

enter image description here
对于以上两种类型的web项目,其资源文件打包以后的路径是一致的,所以获取资源路径的方式也是一致的。

如何获取资源文件的路径

配置文件中加载资源文件

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext/applicationContext.xml</param-value>
</context-param>

就像在web.xml 文件中加在spring的配置文件时,只需要将资源文件的路径前面加上“classpath: “ 即可,“classpath:“ 后面的文件的路径是相对于src/main/resources 或者 WEB-INF 目录的

java类文件中获取资源文件的路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.File;
/**
* web项目打包以后classes文件在磁盘中的绝对路径
* Created by guoenqian on 16/7/13. email:guoeq@jiedaibao.com
*/
public class WebPathUtil {
public static String getWebPath() {
String webPath = "";
File classesFile = new File(WebPathUtil.class.getClassLoader().getResource("").getPath());
webPath = classesFile.getParent() + File.separator + "classes" + File.separator;
return webPath;
}
}

此方法获得web项目打包以后classes文件在磁盘中的绝对路径

总结:我们获得资源文件的路径的原理就是把资源文件的项目路径转化为磁盘的绝对路径,这样拿到文件的路径才是唯一并且正确的。

坚持原创技术分享,您的支持将鼓励我继续创作!

热评文章