KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > util > ResourceLoader


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 JavaDoc;
9 import java.io.FileInputStream JavaDoc;
10 import java.io.FileNotFoundException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.net.URL JavaDoc;
13
14 public 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 JavaDoc loadResourceAsStream(String JavaDoc name) throws RuleSetNotFoundException {
26         InputStream JavaDoc 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 JavaDoc loadResourceAsStream(String JavaDoc name, ClassLoader JavaDoc loader) throws RuleSetNotFoundException {
38         File JavaDoc file = new File JavaDoc(name);
39         if (file.exists()) {
40             try {
41                 return new FileInputStream JavaDoc(file);
42             } catch (FileNotFoundException JavaDoc e) {
43                 // if the file didn't exist, we wouldn't be here
44
}
45         } else {
46             try {
47                 return new URL JavaDoc(name).openConnection().getInputStream();
48             } catch (Exception JavaDoc 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 }
55
Popular Tags