Load resources from the classpath rather than from a base URL.

git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@251 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
Michael Bayne
2001-08-15 02:12:46 +00:00
parent 2cbed37cac
commit 5feef4694b
@@ -1,5 +1,5 @@
// //
// $Id: ResourceManager.java,v 1.1 2001/07/18 21:16:12 mdb Exp $ // $Id: ResourceManager.java,v 1.2 2001/08/15 02:12:46 mdb Exp $
package com.threerings.resource; package com.threerings.resource;
@@ -17,16 +17,22 @@ public class ResourceManager
{ {
/** /**
* Temporary means by which to construct a resource manager that loads * Temporary means by which to construct a resource manager that loads
* resources from the specified source. * resources from the specified source. The resource root is prepended
* to any path that is requested and that fully qualified path is
* searched for in the classpath.
*/ */
public ResourceManager (URL source) public ResourceManager (String resourceRoot)
{ {
_source = source; // keep track of our root path
_rootPath = _source.getPath(); _rootPath = resourceRoot;
// make root path end with a slash // make root path end with a slash
if (!_rootPath.endsWith("/")) { if (!_rootPath.endsWith("/")) {
_rootPath = _rootPath + "/"; _rootPath = _rootPath + "/";
} }
// use the classloader that loaded us
_loader = getClass().getClassLoader();
} }
/** /**
@@ -41,16 +47,13 @@ public class ResourceManager
public InputStream getResource (String path) public InputStream getResource (String path)
throws IOException throws IOException
{ {
try { String rpath = _rootPath + path;
String rpath = _rootPath + path; InputStream in = _loader.getResourceAsStream(rpath);
URL rurl = new URL(_source, rpath); if (in == null) {
return rurl.openStream(); String errmsg = "Unable to locate resource [path=" + rpath + "]";
throw new FileNotFoundException(errmsg);
} catch (MalformedURLException mue) {
Log.warning("Unable to construct path to resource " +
"[path=" + path + "].");
return null;
} }
return in;
} }
/** /**
@@ -92,10 +95,9 @@ public class ResourceManager
public static void main (String[] args) public static void main (String[] args)
{ {
try { try {
String root = System.getProperty("root", ""); ResourceManager rmgr = new ResourceManager("rsrc");
URL url = new URL("file:" + root + "/rsrc"); byte[] data = rmgr.getResourceAsBytes(
ResourceManager rmgr = new ResourceManager(url); "config/miso/miso.properties");
byte[] data = rmgr.getResourceAsBytes("config/miso.properties");
System.out.println(new String(data)); System.out.println(new String(data));
} catch (Exception e) { } catch (Exception e) {
@@ -103,6 +105,6 @@ public class ResourceManager
} }
} }
protected URL _source; protected ClassLoader _loader;
protected String _rootPath; protected String _rootPath;
} }