springboot中关于classpath:路径使用及说明

目录
  • 1. 案例说明
    • 1.1 解决方案
  • 2. ResourceUtils使用说明
    • 2.1 源码展示
    • 2.2 常用方法
  • 3. 常见问题
    • 3.1 打成jar后获取不到文件

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 URL
			return new URL(resourceLocation);
		}
		catch (MalformedURLException ex) {
			// no URL -> treat as file path
			try {
				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 URL
			return getFile(new URL(resourceLocation));
		}
		catch (MalformedURLException ex) {
			// no URL -> treat as file path
			return 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();

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot 如何读取classpath下的文件

    SpringBoot 读取classpath下文件 开发过程中,必不可少的需要读取文件,对于打包方式的不同,还会存在一些坑,比如以jar包方式部署时,文件都存在于jar包中,某些读取方式在开发工程中都可行,但是打包后,由于文件被保存在jar中,会导致读取失败. 这时就需要通过类加载器读取文件,类加载器可以读取jar包中的class类当然也可以读取jar包中的文件. // 方法1:获取文件或流 this.getClass().getResource("/")+fileName; this

  • spring boot加载资源路径配置和classpath问题解决

    1.spring boot默认加载文件的路径: /META-INF/resources/ /resources/ /static/ /public/ 我们也可以从spring boot源码也可以看到: private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classp

  • springboot默认的5种加载路径详解

    目录 前言 一.application.properties/.yml文件初识 二.application.properties/.yml文件可以在其他路径吗 三.总结 前言 上次分享了如何一步一步搭建一个springboot的项目,详细参见<5分钟快速搭建一个springboot的项目>,最终的结果是在”8080“端口搭建起了服务,并成功访问.不知道有小伙伴是否有疑惑,springboot应该有配置文件的,一般的配置文件都是application.properties或者applicatio

  • SpringBoot框架配置文件路径设置方式

    目录 SpringBoot配置文件路径设置 自定义配置文件路径以及多profile配置文件 一.什么是classpath 二.自定义springboot配置文件路径 三.多 profiles 配置文件的切换 SpringBoot配置文件路径设置 选择"Edit Configurations": 下springboot启动配置中修改VM options的值: 值参考: -Dspring.config.location=E:/workspace/xxxx/application.yml -

  • springboot中关于classpath:路径使用及说明

    目录 1. 案例说明 1.1 解决方案 2. ResourceUtils使用说明 2.1 源码展示 2.2 常用方法 3. 常见问题 3.1 打成jar后获取不到文件 1. 案例说明 在 resources下有model.conf文件,在配置文件中使用classpath:做为文件路径 1.1 解决方案 1.1.1 使用ResourcePatternResolver实现 使用classpath:做为路径 通过@value获取配置文件中的路径,后经过ResourcePatternResolver 获

  • springboot中生成文件路径的问题及解决方法

    目录 springboot生成文件路径 举例 springboot创建错误(路径) 解决 springboot生成文件路径 在进行 springboot 项目开发以及打包为 jar 包发布时, 可能会有两种情况下生成文件路径不一致的问题, 有一种获取路径的方法可以使两种环境下都可以正确获取到项目或jar包的根目录 举例 String root = System.getProperty("user.dir"); String path = root +"\\out.txt&qu

  • SpringBoot中配置Web静态资源路径的方法

    介绍: 本文章主要针对web项目中的两个问题进行详细解析介绍:1- 页面跳转404,即controller转发无法跳转页面问题:2- 静态资源文件路径问题. 项目工具: Intelij Idea, JDK1.8, SpringBoot 2.1.3 正文: 准备工作:通过Idea创建一个SpringBoot-web项目,此过程不做赘述,创建完成后项目结构如下图: 1- 创建一个controller代码如下: package com.example.webpractice.controller; i

  • Java中获取类路径classpath的简单方法(推荐)

    如下所示: <SPAN style="FONT-SIZE: 18px"> System.out.println("++++++++++++++++++++++++"); String path = System.getProperty("java.class.path"); String path2 = FreeMarkerWriter.class.getProtectionDomain().getCodeSource().getLo

  • JavaWeb项目中classpath路径详解

    在使用ssh等框架开发web程序时配置文件(xml和properties)存放的路径一般为src下,当部署程序时则必须存在于classes路径下,具体如下 src不是classpath, WEB-INF/classes,lib才是classpath WEB-INF/ 是资源目录, 客户端不能直接访问, 这话是没错,不过现在的IDE编译器在编译时会把src下的文件(是文件,不是.java)移到WEB-INF/classes下.不过值得注意的是,spring配置文件里这个locations是uri表

  • springboot中请求路径配置在配置文件中详解

    目录 请求路径配置在配置文件中 在配置文件中配置访问路径的写法改变了 请求路径配置在配置文件中 原先一直使用springboot,请求路径直接写在@RequestMapping.@GetMapping等注解中,最近,有个比较有趣的发现,原来请求的url其实也可以写在项目的配置文件application.properties或者application.yml,下面记录一下,分享一下. 在配置文件中设置请求路径,我使用yml格式配置文件application.yml my: demo: path:

  • 在SpringBoot中静态资源访问方法

    一.概述 springboot 默认静态资源访问的路径为:/static 或 /public 或 /resources 或 /META-INF/resources 这样的地址都必须定义在src/main/resources目录文件中,这样可以达到在项目启动时候可以自动加载为项目静态地址目录到classpath下 ,静态访问地址其实是使用 ResourceHttpRequestHandler 核心处理器加载到WebMvcConfigurerAdapter进行对addResourceHandlers

  • springboot中swagger快速启动流程

    介绍 可能大家都有用过swagger,可以通过ui页面显示接口信息,快速和前端进行联调. 没有接触的小伙伴可以参考官网文章进行了解下demo页面. 多应用 当然在单个应用大家可以配置SwaggerConfig类加载下buildDocket,就可以快速构建好swagger了. 代码大致如下: /** * Swagger2配置类 * 在与spring boot集成时,放在与Application.java同级的目录下. * 通过@Configuration注解,让Spring来加载该类配置. * 再

  • 详解在springboot中使用Mybatis Generator的两种方式

    介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql.相信很多人都听说过微服务,各个微服务之间是松耦合的.每个微服务仅关注于完成一件任务并很好地完成该任务.在一个微服务的开发过程中很可能只关注对单表的操作.所以MBG在开发过程中可以快速的生成代码提升开发效率. 本文将说到在springboot的项目中如何去配置(XML形式和Java配置类形式)和使用M

  • SpringBoot中的五种对静态资源的映射规则的实现

    SpringBoot中的SpringMVC配置功能都是在WebMvcAutoConfiguration类中,xxxxAutoConfiguration就是帮我们给容器中自动配置组件的:idea全局搜索的快捷键是两次shift,查看webMvcAutoConfiguration 查看webMvc自动配置类 WebMvcAutoConfiguration类的原理以后至少还要稍微掌握,而这里文章只是来看它的具体的关键代码,这里只例举部分关键代码,多了看着也头疼,看不懂没关系哈哈哈可跳过源码阶段,何必徒

随机推荐