获取资源文件工具类

如果没有依赖spring,可以将分割线下的方法去掉

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Properties;public class Resources {private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();private static Charset charset;Resources() {}public static ClassLoader getDefaultClassLoader() {return classLoaderWrapper.defaultClassLoader;}public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {classLoaderWrapper.defaultClassLoader = defaultClassLoader;}public static URL getResourceURL(String resource) throws IOException {return getResourceURL((ClassLoader)null, resource);}public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {URL url = classLoaderWrapper.getResourceAsURL(resource, loader);if(url == null) {throw new IOException("Could not find resource " + resource);} else {return url;}}public static InputStream getResourceAsStream(String resource) throws IOException {return getResourceAsStream((ClassLoader)null, resource);}public static InputStream getResourceAsStream(Class<?> clazz, String resource) throws IOException {InputStream in = classLoaderWrapper.getResourceAsStream(resource, clazz);if(in == null) {throw new IOException("Could not find resource " + resource);} else {return in;}}public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);if(in == null) {throw new IOException("Could not find resource " + resource);} else {return in;}}public static Properties getResourceAsProperties(String resource) throws IOException {Properties props = new Properties();InputStream in = getResourceAsStream(resource);props.load(in);in.close();return props;}public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {Properties props = new Properties();InputStream in = getResourceAsStream(loader, resource);props.load(in);in.close();return props;}public static Reader getResourceAsReader(String resource) throws IOException {InputStreamReader reader;if(charset == null) {reader = new InputStreamReader(getResourceAsStream(resource));} else {reader = new InputStreamReader(getResourceAsStream(resource), charset);}return reader;}public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {InputStreamReader reader;if(charset == null) {reader = new InputStreamReader(getResourceAsStream(loader, resource));} else {reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);}return reader;}public static File getResourceAsFile(String resource) throws IOException {return new File(getResourceURL(resource).getFile());}public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {return new File(getResourceURL(loader, resource).getFile());}public static InputStream getUrlAsStream(String urlString) throws IOException {URL url = new URL(urlString);URLConnection conn = url.openConnection();return conn.getInputStream();}public static Reader getUrlAsReader(String urlString) throws IOException {InputStreamReader reader;if(charset == null) {reader = new InputStreamReader(getUrlAsStream(urlString));} else {reader = new InputStreamReader(getUrlAsStream(urlString), charset);}return reader;}public static Properties getUrlAsProperties(String urlString) throws IOException {Properties props = new Properties();InputStream in = getUrlAsStream(urlString);props.load(in);in.close();return props;}public static Class<?> classForName(String className) throws ClassNotFoundException {return classLoaderWrapper.classForName(className);}public static Charset getCharset() {return charset;}public static void setCharset(Charset charset) {charset = charset;}//############################ 华丽分割线 通过 spring 工具类 #################################public static File getFileWithResourceUtils(String resource) throws FileNotFoundException {return ResourceUtils.getFile(resource);}public Resource getResourceWithPathMatchingResourcePatternResolver(String resource) {PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();return pathMatchingResourcePatternResolver.getResource(resource);}public Resource[] getResourcesWithPathMatchingResourcePatternResolver(String resource) throws IOException {PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();return pathMatchingResourcePatternResolver.getResources(resource);}public InputStream getInputStreamWithClassPathResource(String resource, Class<?> clazz) throws IOException {if (clazz != null) {return new ClassPathResource(resource, clazz).getInputStream();} else {return new ClassPathResource(resource).getInputStream();}}
}class ClassLoaderWrapper {ClassLoader defaultClassLoader;ClassLoader systemClassLoader;ClassLoaderWrapper() {try {this.systemClassLoader = ClassLoader.getSystemClassLoader();} catch (SecurityException var2) {;}}public URL getResourceAsURL(String resource) {return this.getResourceAsURL(resource, this.getClassLoaders((ClassLoader)null));}public URL getResourceAsURL(String resource, ClassLoader classLoader) {return this.getResourceAsURL(resource, this.getClassLoaders(classLoader));}public InputStream getResourceAsStream(String resource) {return this.getResourceAsStream(resource, this.getClassLoaders((ClassLoader)null));}public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {return this.getResourceAsStream(resource, this.getClassLoaders(classLoader));}public Class<?> classForName(String name) throws ClassNotFoundException {return this.classForName(name, this.getClassLoaders((ClassLoader)null));}public Class<?> classForName(String name, ClassLoader classLoader) throws ClassNotFoundException {return this.classForName(name, this.getClassLoaders(classLoader));}InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {ClassLoader[] arr$ = classLoader;int len$ = classLoader.length;for(int i$ = 0; i$ < len$; ++i$) {ClassLoader cl = arr$[i$];if(null != cl) {InputStream returnValue = cl.getResourceAsStream(resource);if(null == returnValue) {returnValue = cl.getResourceAsStream("/" + resource);}if(null != returnValue) {return returnValue;}}}return null;}URL getResourceAsURL(String resource, ClassLoader[] classLoader) {ClassLoader[] arr$ = classLoader;int len$ = classLoader.length;for(int i$ = 0; i$ < len$; ++i$) {ClassLoader cl = arr$[i$];if(null != cl) {URL url = cl.getResource(resource);if(null == url) {url = cl.getResource("/" + resource);}if(null != url) {return url;}}}return null;}Class<?> classForName(String name, ClassLoader[] classLoader) throws ClassNotFoundException {ClassLoader[] arr$ = classLoader;int len$ = classLoader.length;for(int i$ = 0; i$ < len$; ++i$) {ClassLoader cl = arr$[i$];if(null != cl) {try {Class<?> c = Class.forName(name, true, cl);if(null != c) {return c;}} catch (ClassNotFoundException var8) {;}}}throw new ClassNotFoundException("Cannot find class: " + name);}ClassLoader[] getClassLoaders(ClassLoader classLoader) {return new ClassLoader[]{classLoader, this.defaultClassLoader, Thread.currentThread().getContextClassLoader(), this.getClass().getClassLoader(), this.systemClassLoader};}public InputStream getResourceAsStream(String resource, Class<?> clazz) {return clazz.getResourceAsStream(resource);}
}

测试方法

try {File file = ResourceUtils.getFile("classpath:" + Resources.class.getName().replace(".", "/") + ".class");BufferedReader br = new BufferedReader(new FileReader(file));String str = null;while ((str = br.readLine()) != null) {System.out.println(str);}
} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
}try {PathMatchingResourcePatternResolver p = new PathMatchingResourcePatternResolver();BufferedReader br = new BufferedReader(new InputStreamReader(p.getResource(Resources.class.getName().replace(".", "/") + ".class").getInputStream()));String str = null;while ((str = br.readLine()) != null) {System.out.println(str);}
} catch (IOException e) {e.printStackTrace();
}

//classpath 加不加都可以呦
try { PathMatchingResourcePatternResolver p = new PathMatchingResourcePatternResolver(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getResources("classpath:"+Resources.class.getName().replace(".", "/") + ".class")[0].getInputStream())); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(Resources.getResourceAsStream(Resources.class.getName().replace(".", "/") + ".class"))); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(Resources.getResourceAsStream(Resources.class,"Resources.class"))); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(new ClassPathResource(Resources.class.getName().replace(".", "/") + ".class").getInputStream())); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(new ClassPathResource("Resources.class", Resources.class).getInputStream())); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(Resources.getResourceAsStream(Resources.class.getName().replace(".", "/") + ".class"))); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }

 

可以获取到多个,包括我们自己定义的Resources.class

try {PathMatchingResourcePatternResolver p = new PathMatchingResourcePatternResolver();BufferedReader br = new BufferedReader(new InputStreamReader(p.getResources("classpath*:com/**/Resources.class")[0].getInputStream()));String str = null;while ((str = br.readLine()) != null) {System.out.println(str);}
} catch (IOException e) {e.printStackTrace();
}

不可以获取到

try {PathMatchingResourcePatternResolver p = new PathMatchingResourcePatternResolver();BufferedReader br = new BufferedReader(new InputStreamReader(p.getResources("classpath:com/**/Resources.class")[0].getInputStream()));String str = null;while ((str = br.readLine()) != null) {System.out.println(str);}
} catch (IOException e) {e.printStackTrace();
}

原因看一下 方法的源代码就发现了哦!

public Resource[] getResources(String locationPattern) throws IOException {Assert.notNull(locationPattern, "Location pattern must not be null");if(locationPattern.startsWith("classpath*:")) {return this.getPathMatcher().isPattern(locationPattern.substring("classpath*:".length()))?this.findPathMatchingResources(locationPattern):this.findAllClassPathResources(locationPattern.substring("classpath*:".length()));} else {int prefixEnd = locationPattern.indexOf(":") + 1;return this.getPathMatcher().isPattern(locationPattern.substring(prefixEnd))?this.findPathMatchingResources(locationPattern):new Resource[]{this.getResourceLoader().getResource(locationPattern)};}
}

  findPathMatchingResources方法中调用getResources 最后执行的 代码中标红色的部分,通过resourceLoader返回资源。

  classpath*: 和 classpath: 不同的地方看一下getResources方法中 代码中标红色的 部分。 

转载于:https://www.cnblogs.com/hujunzheng/p/7219303.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531246.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

无状态shiro认证组件(禁用默认session)

准备内容 简单的shiro无状态认证 无状态认证拦截器 import com.hjzgg.stateless.shiroSimpleWeb.Constants; import com.hjzgg.stateless.shiroSimpleWeb.realm.StatelessToken; import org.apache.shiro.web.filter.AccessControlFilter;import javax.servlet.ServletRequest;…

Spring根据包名获取包路径下的所有类

参考mybatis MapperScannerConfigurer.java 最终找到 Spring的一个类 ClassPathBeanDefinitionScanner.java 参考ClassPathBeanDefinitionScanner 和它的父类 ClassPathScanningCandidateComponentProvider&#xff0c;将一些代码进行抽取&#xff0c;得到如下工具类。 import…

idea模板注释

类文件头部的注释 #if (${PACKAGE_NAME} && ${PACKAGE_NAME} ! "")package ${PACKAGE_NAME};#end #parse("File Header.java") /** * ${DESCRIPTION} * author ${USER} hujunzheng * create ${YEAR}-${MONTH}-${DAY} ${TIME} **/ public class ${N…

redis分布式锁小试

一、场景 项目A监听mq中的其他项目的部署消息&#xff08;包括push_seq, status, environment&#xff0c;timestamp等&#xff09;&#xff0c;然后将部署消息同步到数据库中&#xff08;项目X在对应环境[environment]上部署的push_seq[项目X的版本]&#xff09;。那么问题来了…

Jackson ObjectMapper readValue过程

1.整体调用栈 2.看一下调用栈的两个方法 resolve 方法中通过 Iterator i$ this._beanProperties.iterator() 遍历属性的所有子属性&#xff0c;缓存对应的 deserializer。观察调用栈的方法&#xff0c;可以发现是循环调用的。 3.比如寻找自定义的 LocalDateTime类的序列化实现…

java如何寻找main函数对应的类

参考springboot Class<?> deduceMainApplicationClass() {try {StackTraceElement[] stackTrace new RuntimeException().getStackTrace();for (StackTraceElement stackTraceElement : stackTrace) {if ("main".equals(stackTraceElement.getMethodName())…

jooq实践

用法 sql语句 SELECT AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, COUNT(*)FROM AUTHORJOIN BOOK ON AUTHOR.ID BOOK.AUTHOR_IDWHERE BOOK.LANGUAGE DEAND BOOK.PUBLISHED > DATE 2008-01-01 GROUP BY AUTHOR.FIRST_NAME, AUTHOR.LAST_NAMEHAVING COUNT(*) > 5 ORDER BY AUT…

git根据用户过滤提交记录

使用SourceTree 使用gitk 转载于:https://www.cnblogs.com/hujunzheng/p/8398203.html

cglib动态代理导致注解丢失问题及如何修改注解允许被继承

现象 SOAService这个bean先后经过两个BeanPostProcessor&#xff0c;会发现代理之后注解就丢失了。 开启了cglib代理 SpringBootApplication EnableAspectJAutoProxy(proxyTargetClass true) public class Application {public static void main(String[] args) {SpringApplic…

spring AbstractBeanDefinition创建bean类型是动态代理类的方式

1.接口 Class<?> resourceClass 2.获取builder BeanDefinitionBuilder builder BeanDefinitionBuilder.genericBeanDefinition(resourceClass); 3.获取接口对应的动态代理class Class<?> targetProxyClass Proxy.getProxyClass(XXX.class.getClassLoader(), ne…

微信小程序:一起玩连线,一个算法来搞定

微信小程序&#xff1a;一起玩连线 游戏玩法 将相同颜色的结点连接在一起&#xff0c;连线之间不能交叉。 算法思想 转换为多个源点到达对应终点的路径问题&#xff0c;且路径之间不相交。按照dfs方式寻找两个结点路径&#xff0c;一条路径探索完之后&#xff0c;标记地图并记录…

IntelliJ IDEA关于logger的live template配置

1.安装 log support2插件 2.配置log support2 由于项目中的日志框架是公司自己封装的&#xff0c;所以还需要自己手动改一下 log support2插件生成的live template 当然也可以修改 Log support global的配置 包括 Logger Field、Logger class、Logger Factory class都可以修改。…

springboot项目接入配置中心,实现@ConfigurationProperties的bean属性刷新方案

前言 配置中心&#xff0c;通过keyvalue的形式存储环境变量。配置中心的属性做了修改&#xff0c;项目中可以通过配置中心的依赖&#xff08;sdk&#xff09;立即感知到。需要做的就是如何在属性发生变化时&#xff0c;改变带有ConfigurationProperties的bean的相关属性。 配置…

简单封装kafka相关的api

一、针对于kafka版本 <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId><version>0.8.2.2</version></dependency><dependency><groupId>org.apache.kafka</groupId>…

springmvc controller动态设置content-type

springmvc RequestMappingHandlerAdapter#invokeHandlerMethod 通过ServletInvocableHandlerMethod#invokeAndHandle调用目标方法&#xff0c;并处理返回值。 如果return value &#xff01; null&#xff0c;则通过returnvalueHandlers处理&#xff0c;内部会调用MessageConv…

springboot2.0 redis EnableCaching的配置和使用

一、前言 关于EnableCaching最简单使用&#xff0c;个人感觉只需提供一个CacheManager的一个实例就好了。springboot为我们提供了cache相关的自动配置。引入cache模块&#xff0c;如下。 二、maven依赖 <dependency><groupId>org.springframework.boot</groupId…

依赖配置中心实现注有@ConfigurationProperties的bean相关属性刷新

配置中心是什么 配置中心&#xff0c;通过keyvalue的形式存储环境变量。配置中心的属性做了修改&#xff0c;项目中可以通过配置中心的依赖&#xff08;sdk&#xff09;立即感知到。需要做的就是如何在属性发生变化时&#xff0c;改变带有ConfigurationProperties的bean的相关属…

java接口签名(Signature)实现方案

预祝大家国庆节快乐&#xff0c;赶快迎接美丽而快乐的假期吧&#xff01;&#xff01;&#xff01; 前言 在为第三方系统提供接口的时候&#xff0c;肯定要考虑接口数据的安全问题&#xff0c;比如数据是否被篡改&#xff0c;数据是否已经过时&#xff0c;数据是否可以重复提交…

Git rebase命令实战

一、前言 一句话&#xff0c;git rebase 可以帮助项目中的提交历史干净整洁&#xff01;&#xff01;&#xff01; 二、避免合并出现分叉现象 git merge操作 1、新建一个 develop 分支 2、在develop分支上新建两个文件 3、然后分别执行 add、commit、push 4、接着切换到master分…

windows系统nexus3安装和配置

一、前言 为什么要在本地开发机器上安装nexus&#xff1f;首先声明公司内部是有自己的nexus仓库&#xff0c;但是对上传jar包做了限制&#xff0c;不能畅快的上传自己测试包依赖。于是就自己在本地搭建了一个nexus私服&#xff0c;即可以使用公司nexus私服仓库中的依赖&#xf…