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