View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package net.sourceforge.pmd.util;
5   
6   import net.sourceforge.pmd.RuleSetNotFoundException;
7   
8   import java.io.File;
9   import java.io.FileInputStream;
10  import java.io.FileNotFoundException;
11  import java.io.InputStream;
12  import java.net.URL;
13  
14  public class ResourceLoader {
15  
16      // Single static method, so we shouldn't allow an instance to be created
17      private ResourceLoader() {
18      }
19  
20      /***
21       *
22       * Method to find a file, first by finding it as a file
23       * (either by the absolute or relative path), then as
24       * a URL, and then finally seeing if it is on the classpath.
25       *
26       */
27      public static InputStream loadResourceAsStream(String name) throws RuleSetNotFoundException {
28          InputStream stream = ResourceLoader.loadResourceAsStream(name, new ResourceLoader().getClass().getClassLoader());
29          if (stream == null) {
30              throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
31          }
32          return stream;
33      }
34  
35      /***
36       *
37       * Uses the ClassLoader passed in to attempt to load the
38       * resource if it's not a File or a URL
39       *
40       */
41      public static InputStream loadResourceAsStream(String name, ClassLoader loader) throws RuleSetNotFoundException {
42          File file = new File(name);
43          if (file.exists()) {
44              try {
45                  return new FileInputStream(file);
46              } catch (FileNotFoundException e) {
47                  // if the file didn't exist, we wouldn't be here
48              }
49          } else {
50              try {
51                  return new URL(name).openConnection().getInputStream();
52              } catch (Exception e) {
53                  return loader.getResourceAsStream(name);
54              }
55          }
56          throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
57      }
58  }