Spring Boot 打包后获取 Classpath 目录下文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.util.Arrays;
import java.util.List;
/**
* 资源工具类
*
* @author tofuwine
* @since 2022/06/24
*/
public final class ResourceUtils {
private ResourceUtils() {
}
/**
* 获取 CLASSPATH 路径下资源文件集合
* <p>
* 返回值 {@link Resource} 的 {@link Resource#isFile()} 方法将会返回 {@code false};
* 对返回值的处理应使用 {@link Resource#getInputStream()}
* <p>
* 如果使用了第三方工具类或高版本 JDK 可以替换此方法中的集合转化的方法。 <br/>
* 例如:
* <ul>
* <li>JDK16+ 可使用 <pre>return Arrays.stream(rpr.getResources(locationPattern)).toList();</pre></li>
* <li>集成 Hutool 可使用 <pre>return CollUtil.toList(rpr.getResources(locationPattern));</pre></li>
* </ul>
*
* @param locationPattern 资源文件 Pattern
* @return 资源集合
* @author tofuwine
* @since 2022/06/24
*/
public static List<Resource> listResources(String locationPattern) {
try {
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(currentClassLoader());
return Arrays.asList(rpr.getResources(locationPattern));
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
/**
* 获取 CLASSPATH 路径下指定资源文件
*
* @param location 资源文件路径
* @return 资源文件
* @author tofuwine
* @since 2022/06/24
*/
public static Resource getResource(String location) {
try {
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(currentClassLoader());
return rpr.getResource(location);
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
/**
* 获取 ClassLoader
*
* @author tofuwine
* @since 2022/06/24
*/
private static ClassLoader currentClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}
|