1. 案例说明

resources下有model.conf文件,在配置文件中使用classpath:做为文件路径

1.1 解决方案

1.1.1 使用ResourcePatternResolver实现

使用classpath:做为路径
通过@value获取配置文件中的路径,后经过ResourcePatternResolver 获取文件

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource resource = resolver.getResource("classpath:model.conf");String path = resource.getFile().getCanonicalPath();

1.1.2 使用 ClassPathResource实现

 ClassPathResource resource = new ClassPathResource("model.conf");String path = resource.getFile().getCanonicalPath();

ClassPathResource使用时,文件路径中不存在classpath:

1.1.3 使用Spring框架中ResourceUtils实现

File file = ResourceUtils.getFile("classpath:model.conf");
String path = file.getCanonicalPath();

2. ResourceUtils使用说明

2.1 源码展示

/*** Utility methods for resolving resource locations to files in the* file system. Mainly for internal use within the framework.** <p>Consider using Spring's Resource abstraction in the core package* for handling all kinds of file resources in a uniform manner.* {@link org.springframework.core.io.ResourceLoader}'s {@code getResource()}* method can resolve any location to a {@link org.springframework.core.io.Resource}* object, which in turn allows one to obtain a {@code java.io.File} in the* file system through its {@code getFile()} method.** @author Juergen Hoeller* @since 1.1.5* @see org.springframework.core.io.Resource* @see org.springframework.core.io.ClassPathResource* @see org.springframework.core.io.FileSystemResource* @see org.springframework.core.io.UrlResource* @see org.springframework.core.io.ResourceLoader*/
public abstract class ResourceUtils {/** Pseudo URL prefix for loading from the class path: "classpath:" */public static final String CLASSPATH_URL_PREFIX = "classpath:";/** URL prefix for loading from the file system: "file:" */public static final String FILE_URL_PREFIX = "file:";/** URL prefix for loading from a jar file: "jar:" */public static final String JAR_URL_PREFIX = "jar:";/** URL prefix for loading from a war file on Tomcat: "war:" */public static final String WAR_URL_PREFIX = "war:";/** URL protocol for a file in the file system: "file" */public static final String URL_PROTOCOL_FILE = "file";/** URL protocol for an entry from a jar file: "jar" */public static final String URL_PROTOCOL_JAR = "jar";/** URL protocol for an entry from a war file: "war" */public static final String URL_PROTOCOL_WAR = "war";/** URL protocol for an entry from a zip file: "zip" */public static final String URL_PROTOCOL_ZIP = "zip";/** URL protocol for an entry from a WebSphere jar file: "wsjar" */public static final String URL_PROTOCOL_WSJAR = "wsjar";/** URL protocol for an entry from a JBoss jar file: "vfszip" */public static final String URL_PROTOCOL_VFSZIP = "vfszip";/** URL protocol for a JBoss file system resource: "vfsfile" */public static final String URL_PROTOCOL_VFSFILE = "vfsfile";/** URL protocol for a general JBoss VFS resource: "vfs" */public static final String URL_PROTOCOL_VFS = "vfs";/** File extension for a regular jar file: ".jar" */public static final String JAR_FILE_EXTENSION = ".jar";/** Separator between JAR URL and file path within the JAR: "!/" */public static final String JAR_URL_SEPARATOR = "!/";/** Special separator between WAR URL and jar part on Tomcat */public static final String WAR_URL_SEPARATOR = "*/";/*** Return whether the given resource location is a URL:* either a special "classpath" pseudo URL or a standard URL.* @param resourceLocation the location String to check* @return whether the location qualifies as a URL* @see #CLASSPATH_URL_PREFIX* @see java.net.URL*/public static boolean isUrl(@Nullable String resourceLocation) {if (resourceLocation == null) {return false;}if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {return true;}try {new URL(resourceLocation);return true;}catch (MalformedURLException ex) {return false;}}/*** Resolve the given resource location to a {@code java.net.URL}.* <p>Does not check whether the URL actually exists; simply returns* the URL that the given location would correspond to.* @param resourceLocation the resource location to resolve: either a* "classpath:" pseudo URL, a "file:" URL, or a plain file path* @return a corresponding URL object* @throws FileNotFoundException if the resource cannot be resolved to a URL*/public static URL getURL(String resourceLocation) throws FileNotFoundException {Assert.notNull(resourceLocation, "Resource location must not be null");if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());ClassLoader cl = ClassUtils.getDefaultClassLoader();URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));if (url == null) {String description = "class path resource [" + path + "]";throw new FileNotFoundException(description +" cannot be resolved to URL because it does not exist");}return url;}try {// try URLreturn new URL(resourceLocation);}catch (MalformedURLException ex) {// no URL -> treat as file pathtry {return new File(resourceLocation).toURI().toURL();}catch (MalformedURLException ex2) {throw new FileNotFoundException("Resource location [" + resourceLocation +"] is neither a URL not a well-formed file path");}}}/*** Resolve the given resource location to a {@code java.io.File},* i.e. to a file in the file system.* <p>Does not check whether the file actually exists; simply returns* the File that the given location would correspond to.* @param resourceLocation the resource location to resolve: either a* "classpath:" pseudo URL, a "file:" URL, or a plain file path* @return a corresponding File object* @throws FileNotFoundException if the resource cannot be resolved to* a file in the file system*/public static File getFile(String resourceLocation) throws FileNotFoundException {Assert.notNull(resourceLocation, "Resource location must not be null");if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());String description = "class path resource [" + path + "]";ClassLoader cl = ClassUtils.getDefaultClassLoader();URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));if (url == null) {throw new FileNotFoundException(description +" cannot be resolved to absolute file path because it does not exist");}return getFile(url, description);}try {// try URLreturn getFile(new URL(resourceLocation));}catch (MalformedURLException ex) {// no URL -> treat as file pathreturn new File(resourceLocation);}}/*** Resolve the given resource URL to a {@code java.io.File},* i.e. to a file in the file system.* @param resourceUrl the resource URL to resolve* @return a corresponding File object* @throws FileNotFoundException if the URL cannot be resolved to* a file in the file system*/public static File getFile(URL resourceUrl) throws FileNotFoundException {return getFile(resourceUrl, "URL");}/*** Resolve the given resource URL to a {@code java.io.File},* i.e. to a file in the file system.* @param resourceUrl the resource URL to resolve* @param description a description of the original resource that* the URL was created for (for example, a class path location)* @return a corresponding File object* @throws FileNotFoundException if the URL cannot be resolved to* a file in the file system*/public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {Assert.notNull(resourceUrl, "Resource URL must not be null");if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {throw new FileNotFoundException(description + " cannot be resolved to absolute file path " +"because it does not reside in the file system: " + resourceUrl);}try {return new File(toURI(resourceUrl).getSchemeSpecificPart());}catch (URISyntaxException ex) {// Fallback for URLs that are not valid URIs (should hardly ever happen).return new File(resourceUrl.getFile());}}/*** Resolve the given resource URI to a {@code java.io.File},* i.e. to a file in the file system.* @param resourceUri the resource URI to resolve* @return a corresponding File object* @throws FileNotFoundException if the URL cannot be resolved to* a file in the file system* @since 2.5*/public static File getFile(URI resourceUri) throws FileNotFoundException {return getFile(resourceUri, "URI");}/*** Resolve the given resource URI to a {@code java.io.File},* i.e. to a file in the file system.* @param resourceUri the resource URI to resolve* @param description a description of the original resource that* the URI was created for (for example, a class path location)* @return a corresponding File object* @throws FileNotFoundException if the URL cannot be resolved to* a file in the file system* @since 2.5*/public static File getFile(URI resourceUri, String description) throws FileNotFoundException {Assert.notNull(resourceUri, "Resource URI must not be null");if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {throw new FileNotFoundException(description + " cannot be resolved to absolute file path " +"because it does not reside in the file system: " + resourceUri);}return new File(resourceUri.getSchemeSpecificPart());}/*** Determine whether the given URL points to a resource in the file system,* i.e. has protocol "file", "vfsfile" or "vfs".* @param url the URL to check* @return whether the URL has been identified as a file system URL*/public static boolean isFileURL(URL url) {String protocol = url.getProtocol();return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) ||URL_PROTOCOL_VFS.equals(protocol));}/*** Determine whether the given URL points to a resource in a jar file.* i.e. has protocol "jar", "war, ""zip", "vfszip" or "wsjar".* @param url the URL to check* @return whether the URL has been identified as a JAR URL*/public static boolean isJarURL(URL url) {String protocol = url.getProtocol();return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_WAR.equals(protocol) ||URL_PROTOCOL_ZIP.equals(protocol) || URL_PROTOCOL_VFSZIP.equals(protocol) ||URL_PROTOCOL_WSJAR.equals(protocol));}/*** Determine whether the given URL points to a jar file itself,* that is, has protocol "file" and ends with the ".jar" extension.* @param url the URL to check* @return whether the URL has been identified as a JAR file URL* @since 4.1*/public static boolean isJarFileURL(URL url) {return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));}/*** Extract the URL for the actual jar file from the given URL* (which may point to a resource in a jar file or to a jar file itself).* @param jarUrl the original URL* @return the URL for the actual jar file* @throws MalformedURLException if no valid jar file URL could be extracted*/public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {String urlFile = jarUrl.getFile();int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);if (separatorIndex != -1) {String jarFile = urlFile.substring(0, separatorIndex);try {return new URL(jarFile);}catch (MalformedURLException ex) {// Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar".// This usually indicates that the jar file resides in the file system.if (!jarFile.startsWith("/")) {jarFile = "/" + jarFile;}return new URL(FILE_URL_PREFIX + jarFile);}}else {return jarUrl;}}/*** Extract the URL for the outermost archive from the given jar/war URL* (which may point to a resource in a jar file or to a jar file itself).* <p>In the case of a jar file nested within a war file, this will return* a URL to the war file since that is the one resolvable in the file system.* @param jarUrl the original URL* @return the URL for the actual jar file* @throws MalformedURLException if no valid jar file URL could be extracted* @since 4.1.8* @see #extractJarFileURL(URL)*/public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {String urlFile = jarUrl.getFile();int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);if (endIndex != -1) {// Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"String warFile = urlFile.substring(0, endIndex);if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {return new URL(warFile);}int startIndex = warFile.indexOf(WAR_URL_PREFIX);if (startIndex != -1) {return new URL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));}}// Regular "jar:file:...myjar.jar!/myentry.txt"return extractJarFileURL(jarUrl);}/*** Create a URI instance for the given URL,* replacing spaces with "%20" URI encoding first.* @param url the URL to convert into a URI instance* @return the URI instance* @throws URISyntaxException if the URL wasn't a valid URI* @see java.net.URL#toURI()*/public static URI toURI(URL url) throws URISyntaxException {return toURI(url.toString());}/*** Create a URI instance for the given location String,* replacing spaces with "%20" URI encoding first.* @param location the location String to convert into a URI instance* @return the URI instance* @throws URISyntaxException if the location wasn't a valid URI*/public static URI toURI(String location) throws URISyntaxException {return new URI(StringUtils.replace(location, " ", "%20"));}/*** Set the {@link URLConnection#setUseCaches "useCaches"} flag on the* given connection, preferring {@code false} but leaving the* flag at {@code true} for JNLP based resources.* @param con the URLConnection to set the flag on*/public static void useCachesIfNecessary(URLConnection con) {con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));}}

2.2 常用方法

2.2.1 extractJarFileURL

public static URL extractJarFileURL(URL jarUrl)

从给定的URL (URL可以指向jar文件中的资源或jar文件本身)中提取实际jar文件的URL

2.2.2 getFile

  • getFile(String resourceLocation):将给定的资源位置解析为java.io.file
  • getFile(URI resourceUri) :将给定的资源位置解析为java.io.file
  • getFile(String resourceLocation) :将给定的资源位置解析为java.io.file
  • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file
  • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file

2.2.3 getURL

getURL(String resourceLocation)

将给定的资源位置解析为java.net.URL

2.2.4 isJarURL

isJarURL(URL url)

确定给定的URL是否指向jar文件中的资源,即具有协议“jar”、“zip”、“wsjar”或“代码源”

2.2.5 isUrl

返回给定资源位置是否是URL:一个特殊的“classpath”伪URL还是一个标准URL。

2.2.6 toURI

  • toURI(String location) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。
  • toURI(URL url) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。

3. 常见问题

3.1 打成jar后获取不到文件

Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
解决方案:

BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){buffer.append(line);
}
String input = buffer.toString();

关于springboot中classpath:路径使用说明相关推荐

  1. 关于JAVA项目中CLASSPATH路径详解

    在dos下编译java程序,就要用到classpath这个概念,尤其是在没有设置环境变量的时候.classpath就是存放.class等编译后文件的路径. javac:如果当前你要编译的java文件中 ...

  2. JAVA项目中classpath路径详解

    classpath是什么路径? 1.classpath指的是类路径,也就是编译之后的target文件夹下的WEB-INF/class文件夹. 2.resources文件夹存放的是各种配置文件,当项目被 ...

  3. java项目中Classpath路径到底指的是哪里?

    1.src不是classpath, WEB-INF/classes,lib才是classpath,WEB-INF/ 是资源目录, 客户端不能直接访问. 2.WEB-INF/classes目录存放src ...

  4. java classpath 目录_关于JAVA项目中CLASSPATH路径详解

    在dos下编译java程序,就要用到classpath这个概念,尤其是在没有设置环境变量的时候.classpath就是存放.class等编译后文件的路径. javac:如果当前你要编译的java文件中 ...

  5. java项目生成manifest_Java项目中classpath路径详解-manifest文件

    项目里用到了classpath路径来引用文件,那么classpath指的是哪里呢 我首先把上面的applicationContext.xml文件放在了src目录下发现可以. 那么classpath到底 ...

  6. Q1:spring-boot中Controller路径无法被访问的问题

    在学习spring-boot入门的第一个例子就是spring-boot-web的一个在页面上输出hello-world的例子,在运行这个例子的时候我遇到了下面这个简单的问题,但是第一次解决还是花了我很 ...

  7. web.xml文件中classpath路径指的哪个路径

    菜鸟程序员Chivalry 2017-04-22 08:34 我们知道,使用maven来管理项目时,需要配置web.xml,会出现classpath的配置,如下图所示: 当然,还有其他的各种配置,这里 ...

  8. maven配置项目根路径_maven中classpath路径(转)

    前几天看见一个大神总结classpath文章,觉得特别有用.所以,特此转载(http://my.oschina.net/GivingOnenessDestiny/blog/603505) 各种path ...

  9. SpringBoot项目中的 ClassPath路径指的是哪个路径

    针对SpringBoot项目来说,ClassPath指的是哪些路径 首先,对于SpringBoot项目来说,classpath指的是src.main.java和src.main.resources路径 ...

最新文章

  1. 汇编语言将数据、代码、栈放入不同段基础
  2. RDKit | 基于分子指纹的相似性图
  3. Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
  4. 企业网络推广专员表示在企业网络推广中网站排名优化靠技巧
  5. jQuery学习笔记--JqGrid相关操作 方法列表 备忘 重点讲解(超重要)
  6. Flume原理及使用案例
  7. C++ 引用计数技术简介(1)
  8. Python – numpy.arange()
  9. thinkphp 又一问题
  10. 学生HTML个人网页作业作品:基于web在线汽车网站的设计与实现 (宝马轿车介绍)
  11. php计算ip掩码,php进行ip地址掩码运算处理的方法
  12. H5 video 自动播放(autoplay)不生效解决方案
  13. indiegogo众筹代理经验分享
  14. 【CodingNoBorder - 07】无际软工队 - 求职岛:ALPHA 阶段测试报告
  15. 更换新电池对iPhone手机性能的影响实测
  16. ubuntu 18.04 安装NVIDIA驱动 cuda/cudnn + tensorflow-gpu + pytorch
  17. sql中向下取整怎么取_Sql Server 里的向上取整、向下取整、四舍五入取整的实例! | 学步园...
  18. 微服务架构,这一篇就够了!
  19. didi.github.io 域名无法打开解决办法
  20. hwd分别是长宽高_DS-2CD7A47HWD-XZS 海康威视400万人脸比对摄像机 DS-2CD7A47HWD-XZS/JM

热门文章

  1. WPF 关键字高亮实现方式
  2. Path环境变量的配置
  3. 重装系统后使用VirtualBox新建虚拟机时遇到的错误—创建VirtualBoxClient COM对象失败
  4. 寻找猴王小游戏php代码
  5. 什么是 .manifest 文件
  6. CentOS7 下处理挖矿僵尸网络dota3木马攻击
  7. 2023年07月编程语言流行度排名
  8. 检查xml格式的linux自带方便好用的工具
  9. SVG(可缩放矢量图形)绘制工具Method Draw
  10. 数据结构期末考试题库