获取资源文件工具类

如果没有依赖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:com\/**\/Resources.class找不到, 要换成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();
}
时间: 2024-11-05 16:24:40

获取资源文件工具类的相关文章

15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)

资源文件工具类把sql脚本转换为String字符串--->交给sql工具类ExecSQLUtil执行sql 1.资源文件工具类(ResourceUtil) 把sql脚本转换为String字符串 /** * 资源文件工具类 */ public class ResourceUtil { /** * 以String方式读取整个资源串 */ public static String readResourceAsString(String resource ,String charset) throws

servlet和普通类获取资源文件的方法

package cn.servlet.demo1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Properties; import javax.servlet

java中IO写文件工具类

下面是一些根据常用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 其中jodd中提供的JavaUtil类中提供的方法足够我们使用,里面的方法写的非常简练,例如append,read等方法,封装更好,更符合面向对象, 这里面我写的一些方法可多都是模仿jodd,从里面进行抽取出来的. /** * 获取路径文件夹下的所有文件 * @param path * @return */ public static File[] ge

资源访问工具类

---------------siwuxie095 JDK 所提供的访问资源的类,并不能很好的满足各种底层资源的访问需求, 如:缺少从类路径 或 Web 容器的上下文中获取资源的操作类 因此,Spring 设计了一个 Resource 接口,它为应用提供了更强大的访问 底层资源的能力,该接口拥有对应不同资源类型的实现类 Resource 接口的主要方法: (1)boolean exists():判断资源是否存在 (2)boolean isOpen():判断资源是否已经打开 (3)URL getU

读取Config文件工具类 PropertiesConfig.java

package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; /** * 读取Config文件工具类 * @version 1.0 * @since JDK 1.6 */ public class PropertiesConfig { /** * 获取整个配置文件中的属性 *

httputil用http获取请求的工具类

原文:httputil用http获取请求的工具类 源代码下载地址:http://www.zuidaima.com/share/1550463738612736.htm package com.zuidaima.xiaocan.demo.util; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.

自动扫描FTP文件工具类 ScanFtp.java

package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 自动扫描FTP文件工具类 * 需要定时执行 */ public class S

wpf 前台获取资源文件路径问题

1 <ImageBrush ImageSource="YT.CM.CommonUI;component/Resource/FloadwindowImage/middle.png"/> YT.CM.CommonUI  这是一个类库名字 Resource 这是类库下的文件夹 FloadwindowImage 是Resource下的文件夹 middle.png 是FloadwindowImage下的一张图片 若在使用上句在wpf前台获取该类库下的文件夹中的图片资源,可能会报该路径

android 获取手机信息工具类

package com.yqy.yqy_listviewheadview; import android.content.Context; import android.telephony.TelephonyManager; import android.util.Log; /** * 获取手机信息工具类<br> * 内部已经封装了打印功能,仅仅须要把DEBUG參数改为true就可以<br> * 假设须要更换tag能够直接更改,默觉得KEZHUANG * * @author YQY