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

This page was automatically generated by Maven