1 5 package xdoclet.util; 6 7 import java.io.ByteArrayOutputStream ; 8 import java.io.File ; 9 import java.io.FileNotFoundException ; 10 import java.io.FileOutputStream ; 11 import java.io.IOException ; 12 import java.io.InputStream ; 13 import java.io.OutputStream ; 14 import java.net.URL ; 15 import java.util.HashMap ; 16 import java.util.Map ; 17 import org.apache.commons.logging.Log; 18 19 import xdoclet.XDocletMessages; 20 21 31 public final class FileManager 32 { 33 34 private final static int BUFFER_SIZE = 10240; 35 36 private final static Map urlCache = new HashMap (); 37 38 44 public static synchronized String getURLContent(URL url) 45 { 46 Log log = LogUtil.getLog(FileManager.class, "getURLContent"); 47 48 if (url == null) { 49 throw new IllegalArgumentException ("url shouldn't be null!"); 50 } 51 52 String content = (String ) urlCache.get(url); 53 54 if (content != null) { 55 return content; 56 } 57 58 try { 59 InputStream is = null; 60 61 if ("file".equals(url.getProtocol())) { 62 is = new java.io.FileInputStream (url.getFile()); 63 } 64 else { 65 is = url.openStream(); 66 } 67 68 ByteArrayOutputStream baos = new ByteArrayOutputStream (is.available()); 69 70 pump(is, baos); 71 72 content = new String (baos.toByteArray()); 73 urlCache.put(url, content); 74 75 return content; 76 } 77 catch (FileNotFoundException e) { 78 return null; 79 } 80 catch (Exception e) { 81 e.printStackTrace(); 82 log.error(Translator.getString(XDocletMessages.class, XDocletUtilMessages.EXCEPTION_READING_MERGE_FILE, new String []{e.toString()})); 83 return null; 84 } 85 } 86 87 94 public static synchronized void writeURLContent(URL url, File destination) throws IOException 95 { 96 FileOutputStream fos = new FileOutputStream (destination); 97 98 pump(url.openStream(), fos); 99 fos.flush(); 100 fos.close(); 101 } 102 103 110 private static void pump(InputStream is, OutputStream os) throws IOException 111 { 112 byte[] buffer = new byte[BUFFER_SIZE]; 113 int lengthRead; 114 115 while ((lengthRead = is.read(buffer)) >= 0) { 116 os.write(buffer, 0, lengthRead); 117 } 118 } 119 } 120 | Popular Tags |