Preferred way of loading resources in Java

前端 未结 5 1654
走了就别回头了
走了就别回头了 2020-11-22 15:25

I would like to know the best way of loading a resource in Java:

  • this.getClass().getResource() (or getResourceAsStream()),
  • Thread.c
5条回答
  •  时光取名叫无心
    2020-11-22 15:42

    I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

    public class ResourceLoader {
    
        public static URL getResource(String resource) {
            final List classLoaders = new ArrayList();
            classLoaders.add(Thread.currentThread().getContextClassLoader());
            classLoaders.add(ResourceLoader.class.getClassLoader());
    
            for (ClassLoader classLoader : classLoaders) {
                final URL url = getResourceWith(classLoader, resource);
                if (url != null) {
                    return url;
                }
            }
    
            final URL systemResource = ClassLoader.getSystemResource(resource);
            if (systemResource != null) {
                return systemResource;
            } else {
                try {
                    return new File(resource).toURI().toURL();
                } catch (MalformedURLException e) {
                    return null;
                }
            }
        }
    
        private static URL getResourceWith(ClassLoader classLoader, String resource) {
            if (classLoader != null) {
                return classLoader.getResource(resource);
            }
            return null;
        }
    
    }
    

提交回复
热议问题