获取资源文件工具类

如果没有依赖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…

java8 Optional正确使用姿势

Java 8 如何正确使用 Optional import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils;import java.util.Optional;Data EqualsAndHashCode(exclude{"self"}) ToString(callSupertrue, exclud…

idea springboot热部署无效问题

Intellij IDEA 使用Spring-boot-devTools无效解决办法 springboot项目中遇到的bug <dependencies><!--spring boot 热加载--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId&g…

lintcode 单词接龙II

题意 给出两个单词&#xff08;start和end&#xff09;和一个字典&#xff0c;找出所有从start到end的最短转换序列 比如&#xff1a; 1、每次只能改变一个字母。 2、变换过程中的中间单词必须在字典中出现。 注意事项 所有单词具有相同的长度。所有单词都只包含小写字母。样例…

lintcode 最大子数组III

题目描述 给定一个整数数组和一个整数 k&#xff0c;找出 k 个不重叠子数组使得它们的和最大。每个子数组的数字在数组中的位置应该是连续的。 返回最大的和。 注意事项 子数组最少包含一个数 样例 给出数组 [-1,4,-2,3,-2,3] 以及 k 2&#xff0c;返回 8 思路 dp[i][j] max(…

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…

不同包下,相同数据结构的两个类进行转换

import com.alibaba.fastjson.JSON; JSON.parseObject(JSON.toJSONString(obj1), obj2.class) import com.fasterxml.jackson.databind.ObjectMapper; objectMapper.convertValue(obj1, obj2.class); 两个工具类 JsonUtil JacksonHelper 转载于:https://www.cnblogs.com/hujunz…

git根据用户过滤提交记录

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

springboot Autowired BeanNotOfRequiredTypeException

现象 org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named xxxxImpl is expected to be of type com.xxx.xxxImpl but was actually of type com.sun.proxy.$Proxy62 直接Autowired一个实现类&#xff0c;而不是接口 Autowired private XxxServiceI…

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…

TypeReference -- 让Jackson Json在List/Map中识别自己的Object

private Map<String, Object> buildHeaders(Object params) {ObjectMapper objectMapper JacksonHelper.getMapper();return objectMapper.convertValue(params, new TypeReference<Map<String, Object>>(){}); } 参考How to use Jackson to deserialis…

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

微信小程序&#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的相关属性。 配置…