1 36 37 import java.io.*; 38 import java.net.*; 39 import java.nio.channels.*; 40 import java.nio.charset.*; 41 42 49 class FileContent implements Content { 50 51 private static File ROOT = new File("root"); 52 53 private File fn; 54 55 FileContent(URI uri) { 56 fn = new File(ROOT, 57 uri.getPath() 58 .replace('/', 59 File.separatorChar)); 60 } 61 62 private String type = null; 63 64 public String type() { 65 if (type != null) 66 return type; 67 String nm = fn.getName(); 68 if (nm.endsWith(".html")) 69 type = "text/html; charset=iso-8859-1"; 70 else if ((nm.indexOf('.') < 0) || nm.endsWith(".txt")) 71 type = "text/plain; charset=iso-8859-1"; 72 else 73 type = "application/octet-stream"; 74 return type; 75 } 76 77 private FileChannel fc = null; 78 private long length = -1; 79 private long position = -1; 81 public long length() { 82 return length; 83 } 84 85 public void prepare() throws IOException { 86 if (fc == null) 87 fc = new RandomAccessFile(fn, "r").getChannel(); 88 length = fc.size(); 89 position = 0; } 91 92 public boolean send(ChannelIO cio) throws IOException { 93 if (fc == null) 94 throw new IllegalStateException (); 95 if (position < 0) throw new IllegalStateException (); 97 98 101 if (position >= length) { 102 return false; 103 } 104 105 position += cio.transferTo(fc, position, length - position); 106 return (position < length); 107 } 108 109 public void release() throws IOException { 110 if (fc != null) { 111 fc.close(); 112 fc = null; 113 } 114 } 115 } 116 | Popular Tags |