|
| 1 | +package io.kimmking.java8; |
| 2 | + |
| 3 | +import lombok.SneakyThrows; |
| 4 | + |
| 5 | +import java.io.BufferedReader; |
| 6 | +import java.io.InputStream; |
| 7 | +import java.io.InputStreamReader; |
| 8 | + |
| 9 | +public class ResourceLoader { |
| 10 | + |
| 11 | + static String file = "conf/a.properties"; |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + |
| 15 | + // testClassLoaderRootPath(); // classloader方式不能加根路径,否则文件路径会直接被替换掉最终成了 /conf/a.properties |
| 16 | + testClassLoader(); // 从当前的classpath,不管是 文件夹,还是jar里去找 资源 |
| 17 | + testClassRootPath(); // 判断第一个字符是根路径,去掉根,转成 testClassLoader 调用 |
| 18 | + // testClass(); // class 方式必须加根路径,不加根会根据类路径io.kimmking.java8.ResourceLoader 去拼成 io/kimmking/java8/conf/a.properties |
| 19 | + |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + private static void testClassLoader() { |
| 24 | + System.out.println("====> testClassLoader"); |
| 25 | + loadStream(ResourceLoader.class.getClassLoader().getResourceAsStream(file)); |
| 26 | + } |
| 27 | + |
| 28 | + private static void testClassLoaderRootPath() { |
| 29 | + System.out.println("====> testClassLoader"); |
| 30 | + loadStream(ResourceLoader.class.getClassLoader().getResourceAsStream("/"+file)); |
| 31 | + } |
| 32 | + |
| 33 | + private static void testClass() { |
| 34 | + System.out.println("====> testClass"); |
| 35 | + loadStream(ResourceLoader.class.getResourceAsStream(file)); |
| 36 | + } |
| 37 | + |
| 38 | + private static void testClassRootPath() { |
| 39 | + System.out.println("====> testClassRootPath"); |
| 40 | + loadStream(ResourceLoader.class.getResourceAsStream("/"+file)); |
| 41 | + } |
| 42 | + |
| 43 | + @SneakyThrows |
| 44 | + private static void loadStream(InputStream in) { |
| 45 | + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); |
| 46 | + StringBuffer buffer = new StringBuffer(); |
| 47 | + String line = null; |
| 48 | + while ((line = reader.readLine()) != null) { |
| 49 | + buffer.append(line); |
| 50 | + } |
| 51 | + System.out.println(buffer.toString()); |
| 52 | + reader.close(); |
| 53 | + in.close(); |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments