1 16 package org.mortbay.html; 17 import java.io.BufferedReader ; 18 import java.io.File ; 19 import java.io.FileNotFoundException ; 20 import java.io.FileReader ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.io.InputStreamReader ; 24 import java.io.Reader ; 25 import java.io.StringReader ; 26 import java.io.StringWriter ; 27 import java.io.Writer ; 28 import java.net.URL ; 29 30 import org.apache.commons.logging.Log; 31 import org.mortbay.log.LogFactory; 32 import org.mortbay.util.IO; 33 34 35 43 public class Include extends Element 44 { 45 private static Log log = LogFactory.getLog(Include.class); 46 47 Reader reader=null; 48 49 50 56 public Include(String directory, 57 String fileName) 58 throws IOException 59 { 60 if (directory==null) 61 directory="."; 62 63 if (File.separatorChar != '/') 64 { 65 directory = directory.replace('/',File.separatorChar); 66 fileName = fileName .replace('/',File.separatorChar); 67 } 68 69 if(log.isDebugEnabled())log.debug("IncludeTag("+directory+","+fileName+")"); 70 includeFile(new File (directory,fileName)); 71 } 72 73 74 79 public Include(String fileName) 80 throws IOException 81 { 82 if (File.separatorChar != '/') 83 fileName = fileName .replace('/',File.separatorChar); 84 if(log.isDebugEnabled())log.debug("IncludeTag("+fileName+")"); 85 includeFile(new File (fileName)); 86 } 87 88 89 94 public Include(File file) 95 throws IOException 96 { 97 if(log.isDebugEnabled())log.debug("IncludeTag("+file+")"); 98 includeFile(file); 99 } 100 101 102 110 public Include(InputStream in) 111 throws IOException 112 { 113 if (in!=null) 114 reader=new InputStreamReader (in); 115 } 116 117 118 126 public Include(URL url) 127 throws IOException 128 { 129 if (url!=null) 130 reader=new InputStreamReader (url.openStream()); 131 } 132 133 134 139 public Include(Reader in) 140 throws IOException 141 { 142 reader=in; 143 } 144 145 146 private void includeFile(File file) 147 throws IOException 148 { 149 if (!file.exists()) 150 throw new FileNotFoundException (file.toString()); 151 152 if (file.isDirectory()) 153 { 154 List list = new List(List.Unordered); 155 String [] ls = file.list(); 156 for (int i=0 ; i< ls.length ; i++) 157 list.add(ls[i]); 158 StringWriter sw = new StringWriter (); 159 list.write(sw); 160 reader = new StringReader (sw.toString()); 161 } 162 else 163 { 164 reader = new BufferedReader (new FileReader (file)); 165 } 166 } 167 168 169 170 public void write(Writer out) 171 throws IOException 172 { 173 if (reader==null) 174 return; 175 176 try{ 177 IO.copy(reader,out); 178 } 179 finally 180 { 181 reader.close(); 182 reader=null; 183 } 184 } 185 } 186 187 188 189 190 191 192 193 194 195 | Popular Tags |