1 7 8 package org.jboss.media.util; 9 10 import java.io.ByteArrayOutputStream ; 11 import java.io.File ; 12 import java.io.FileOutputStream ; 13 import java.io.IOException ; 14 import java.io.InputStream ; 15 import java.io.OutputStream ; 16 import java.io.StringWriter ; 17 import java.net.URL ; 18 19 import org.jboss.util.stream.Streams; 20 21 27 public class ResourceUtils 28 { 29 public static InputStream createStreamFromResource(String resourceName) 30 { 31 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 32 return classLoader.getResourceAsStream(resourceName); 33 } 34 35 public static File createFileFromResource( 36 String resourceName, 37 String filePrefix, 38 String fileSuffix) 39 throws IOException 40 { 41 InputStream inputStream = createStreamFromResource(resourceName); 42 43 try 44 { 45 File tempFile = File.createTempFile(filePrefix, fileSuffix); 46 tempFile.deleteOnExit(); 47 OutputStream tempFileStream = new FileOutputStream (tempFile); 48 49 try 50 { 51 Streams.copyb(inputStream, tempFileStream); 52 } 53 finally 54 { 55 tempFileStream.close(); 56 } 57 58 return tempFile; 59 } 60 finally 61 { 62 inputStream.close(); 63 } 64 } 65 66 72 public static byte[] loadBinaryData(String resourceName) throws IOException 73 { 74 InputStream inputStream = 75 ResourceUtils.createStreamFromResource(resourceName); 76 77 try 78 { 79 ByteArrayOutputStream ouputStream = new ByteArrayOutputStream (); 80 try 81 { 82 int byteRead; 83 while ((byteRead = inputStream.read()) != -1) 84 ouputStream.write(byteRead); 85 return ouputStream.toByteArray(); 86 } 87 finally 88 { 89 ouputStream.close(); 90 } 91 } 92 finally 93 { 94 inputStream.close(); 95 } 96 } 97 98 104 public static String loadTextData(String resourceName) throws IOException 105 { 106 InputStream inputStream = 107 ResourceUtils.createStreamFromResource(resourceName); 108 109 try 110 { 111 StringWriter stringWriter = new StringWriter (); 112 try 113 { 114 int byteRead; 115 while ((byteRead = inputStream.read()) != -1) 116 stringWriter.write(byteRead); 117 return stringWriter.toString(); 118 } 119 finally 120 { 121 stringWriter.close(); 122 } 123 } 124 finally 125 { 126 inputStream.close(); 127 } 128 } 129 130 public static InputStream getResourceStream(String resource) 131 { 132 return Thread 133 .currentThread() 134 .getContextClassLoader() 135 .getResourceAsStream( 136 resource); 137 } 138 139 public static File getResourceFile(String resource) 140 { 141 URL u = 142 Thread.currentThread().getContextClassLoader().getResource(resource); 143 String file = u.toExternalForm(); 144 return new File (file.substring(6, file.length())); 145 } 146 } 147 | Popular Tags |