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  /**
    15   */
    16  public final class ResourceLoader {
    17
    18      // Only static methods, so we shouldn't allow an instance to be created
    19      /**
    20       * Constructor for ResourceLoader.
    21       */
    22      private ResourceLoader() {
    23      }
    24
    25      /**
    26       * Method to find a file, first by finding it as a file
    27       * (either by the absolute or relative path), then as
    28       * a URL, and then finally seeing if it is on the classpath.
    29       * @param name String
    30       * @return InputStream
    31       * @throws RuleSetNotFoundException
    32       */
    33      public static InputStream loadResourceAsStream(String name) throws RuleSetNotFoundException {
    34          InputStream stream = loadResourceAsStream(name, ResourceLoader.class.getClassLoader());
    35          if (stream == null) {
    36              throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
    37          }
    38          return stream;
    39      }
    40
    41      /**
    42       * Uses the ClassLoader passed in to attempt to load the
    43       * resource if it's not a File or a URL
    44       * @param name String
    45       * @param loader ClassLoader
    46       * @return InputStream
    47       * @throws RuleSetNotFoundException
    48       */
    49      public static InputStream loadResourceAsStream(String name, ClassLoader loader) throws RuleSetNotFoundException {
    50          File file = new File(name);
    51          if (file.exists()) {
    52              try {
    53                  return new FileInputStream(file);
    54              } catch (FileNotFoundException e) {
    55                  // if the file didn't exist, we wouldn't be here
    56              }
    57          } else {
    58              try {
    59                  return new URL(name).openConnection().getInputStream();
    60              } catch (Exception e) {
    61                  return loader.getResourceAsStream(name);
    62              }
    63          }
    64          throw new RuleSetNotFoundException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
    65      }
    66  }