1 29 30 package nextapp.echo2.webrender.util; 31 32 import java.io.ByteArrayOutputStream ; 33 import java.io.IOException ; 34 import java.io.InputStream ; 35 36 39 public class Resource { 40 41 private static final int BUFFER_SIZE = 4096; 42 43 47 public static class ResourceException extends RuntimeException { 48 49 54 private ResourceException(String description) { 55 super(description); 56 } 57 } 58 59 65 public static String getResourceAsString(String resourceName) { 66 return getResource(resourceName).toString(); 67 } 68 69 75 public static byte[] getResourceAsByteArray(String resourceName) { 76 return getResource(resourceName).toByteArray(); 77 } 78 79 87 private static ByteArrayOutputStream getResource(String resourceName) { 88 InputStream in = null; 89 byte[] buffer = new byte[BUFFER_SIZE]; 90 ByteArrayOutputStream out = null; 91 int bytesRead = 0; 92 93 try { 94 in = Resource.class.getResourceAsStream(resourceName); 95 if (in == null) { 96 throw new ResourceException("Resource does not exist: \"" + resourceName + "\""); 97 } 98 out = new ByteArrayOutputStream (); 99 do { 100 bytesRead = in.read(buffer); 101 if (bytesRead > 0) { 102 out.write(buffer, 0, bytesRead); 103 } 104 } while (bytesRead > 0); 105 } catch (IOException ex) { 106 throw new ResourceException("Cannot get resource: \"" + resourceName + "\": " + ex); 107 } finally { 108 if (in != null) { try { in.close(); } catch (IOException ex) { } } 109 } 110 111 return out; 112 } 113 114 115 private Resource() { } 116 } 117 | Popular Tags |