KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > resource > FileResource


1 package org.sapia.resource;
2
3 import java.io.File JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.InputStream JavaDoc;
7 import java.net.MalformedURLException JavaDoc;
8 import java.net.URI JavaDoc;
9 import java.net.URISyntaxException JavaDoc;
10
11 /**
12  * Implements a <code>Resource</code> over a <code>File</code>
13  *
14  * @see java.io.File
15  *
16  * @author Yanick Duchesne
17  */

18 public class FileResource implements Resource {
19   private File JavaDoc _file;
20
21   public FileResource(File JavaDoc f) {
22     _file = f;
23   }
24   
25   public String JavaDoc getURI() {
26     try {
27       return _file.toURL().toExternalForm();
28     } catch(MalformedURLException JavaDoc e) {
29       throw new IllegalStateException JavaDoc("Could not create URL from resource: "
30           + _file.getAbsolutePath() + "; caught: " + e.getClass().getName()
31           + " - " + e.getMessage());
32     }
33   }
34   
35   public Resource getRelative(String JavaDoc uri) throws IOException JavaDoc {
36     try{
37       if(Utils.hasScheme(uri)){
38         URI JavaDoc u = new URI JavaDoc(uri);
39         if(Utils.isAbsolute(u)){
40           throw new IOException JavaDoc("URI is absolute: " + uri + "; must be relative");
41         }
42       }
43       File JavaDoc relative;
44       if(_file != null){
45         relative = new File JavaDoc(Utils.getRelativePath(_file.getAbsolutePath(), uri, true));
46         if(!relative.exists()){
47           relative = new File JavaDoc(uri);
48         }
49       }
50       else{
51         relative = new File JavaDoc(uri);
52       }
53       return new FileResource(relative);
54     }catch(URISyntaxException JavaDoc e){
55       throw new IOException JavaDoc(e.getMessage());
56     }
57   }
58
59   public InputStream JavaDoc getInputStream() throws IOException JavaDoc {
60     return new FileInputStream JavaDoc(_file);
61   }
62
63   public long lastModified() {
64     return _file.lastModified();
65   }
66
67   public String JavaDoc toString() {
68     return _file.getAbsolutePath();
69   }
70 }
71
Popular Tags