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