01: package org.jicengine.io;
02:
03: import java.io.InputStream;
04: import java.io.File;
05: import java.io.IOException;
06: import java.io.FileNotFoundException;
07: import java.util.StringTokenizer;
08:
09: /**
10: * A resource found in the classpath. The classloader of this
11: * ClassPathResource is used for reading the resource.
12: *
13: *
14: * <p>
15: * Copyright (C) 2004 Timo Laitinen
16: * </p>
17: *
18: * @author Timo Laitinen
19: * @created 2004-09-20
20: * @since JICE-0.10
21: * @version 1.0
22: * @see java.lang.Class
23: * @see java.lang.ClassLoader
24: * @see java.lang.Class#getResourceAsStream
25: * @see java.lang.Class#getResource
26: */
27:
28: public class ClasspathResource extends AbstractResource implements
29: UrlReadable {
30:
31: private ClassLoader classLoader;
32: private String resourceName;
33:
34: /**
35: * The name of the resource, for method ClassLoader.getResourceAsStream().
36: * @see java.lang.Class#getResourceAsStream
37: * @see java.lang.Class#getResource
38: */
39: public ClasspathResource(String resourceName) {
40: super ("classpath://" + resourceName);
41: this .classLoader = getClass().getClassLoader();
42: this .resourceName = resourceName;
43: }
44:
45: public ClasspathResource(ClassLoader classLoader,
46: String resourceName) {
47: super ("classpath://" + resourceName);
48: this .classLoader = classLoader;
49: this .resourceName = resourceName;
50: }
51:
52: public ClassLoader getClassLoader() {
53: return this .classLoader;
54: }
55:
56: public String getResourceName() {
57: return this .resourceName;
58: }
59:
60: public java.net.URL getUrl() throws IOException {
61: java.net.URL url = getClassLoader().getResource(
62: getResourceName());
63: if (url != null) {
64: return url;
65: } else {
66: throw new FileNotFoundException("Resource '"
67: + getResourceName()
68: + "' not available in classpath.");
69: }
70: }
71:
72: public boolean isAvailable() {
73: if (getClassLoader().getResource(getResourceName()) != null) {
74: return true;
75: } else {
76: return false;
77: }
78: }
79:
80: public InputStream getInputStream() throws java.io.IOException {
81: InputStream stream = getClassLoader().getResourceAsStream(
82: getResourceName());
83:
84: if (stream != null) {
85: return stream;
86: } else {
87: throw new java.io.IOException("Resource '"
88: + getResourceName()
89: + "' not available in classpath.");
90: }
91: }
92:
93: public Resource getResource(String relativePath)
94: throws java.io.IOException {
95: return new ClasspathResource(PathResolver.getRealPath(
96: getResourceName(), relativePath));
97: }
98: }
|