獲取資源文件工具類

如果沒有依賴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.pswp.cn/news/531246.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/531246.shtml
英文地址,請注明出處:http://en.pswp.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的相關屬性。 配置…