“mitao”
2026-04-07 3ee4725e50f2494fc291ba841730942004e22956
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
74
75
76
77
78
79
80
81
82
package com.xiaopeng.trafficControl.util;
 
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
 
/**
 * 资源工具类
 * @author binghuoliu
 * 
 */
public class ResourceUtil {
 
    /**
     * 读取classpath下的文件<br>
     * 读取classpath下的文件 一般用于读取classpath下的配置文件,注意读取的配置文件路径是相对传入参数clazz的load入路径. 例:<br>
     * ClassTest c1;//假设c1是从/usr/local/classpath/ 载入<br>
     * ClassTest c2;//假设c2是从/home/classpath/ 载入<br>
     * ............<br>
     * loadConfigFile("a.xml",c1.class);//从/usr/local/classpath1/下寻找a.xml<br>
     * loadConfigFile("a.xml",c2.class);//从/home/classpath/下寻找a.xml<br>
     * @param resource 资源路径
     * @param clazz
     * @return InputStream 文件的inputstram,如果找不到则返回null
     */
    @SuppressWarnings("unchecked")
    public static InputStream loadConfigFile(String resource, Class clazz) {
        ClassLoader classLoader = null;
        try {
            Method method = Thread.class.getMethod("getContextClassLoader");
            classLoader = (ClassLoader) method.invoke(Thread.currentThread());
        } catch (Exception e) {
            throw new RuntimeException("loadConfigFile error: ", e);
        }
        if (classLoader == null) {
            classLoader = clazz.getClassLoader();
        }
        try {
            if (classLoader != null) {
                URL url = classLoader.getResource(resource);
                if (url == null) {
                    System.out.println("Can not find resource:" + resource);
                    return null;
                }
                if (url.toString().startsWith("jar:file:")) {
                    System.out.println("Get resource \"" + resource + "\" from jar:\t" + url.toString());
                    return clazz.getResourceAsStream(resource.startsWith("/") ? resource : "/" + resource);
                } else {
                    System.out.println("Get resource \"" + resource + "\" from:\t" + url.toString());
                    return new FileInputStream(new File(url.toURI()));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("loadConfigFile error: ", e);
        }
        return null;
    }
 
    /**
     * 释放资源(有异常抛出)
     * @param closeable
     * @throws IOException
     */
    public static void close(Closeable closeable) throws IOException {
        if (closeable != null) {
            closeable.close();
        }
    }
 
    /**
     * 以优雅的形式释放资源(内部吃掉了异常)
     * @param closeable
     */
    public static void closeGracefully(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }
}