1 5 package org.exoplatform.commons.utils; 6 7 import java.io.* ; 8 import java.net.URL ; 9 10 16 public class IOUtil { 17 static public String getFileContenntAsString(File file, String encoding) throws Exception { 18 FileInputStream is = new FileInputStream(file) ; 19 return new String (getStreamContentAsBytes(is), encoding) ; 20 } 21 22 static public String getFileContenntAsString(File file) throws Exception { 23 FileInputStream is = new FileInputStream(file) ; 24 return new String (getStreamContentAsBytes(is)) ; 25 } 26 27 static public String getFileContenntAsString(String fileName, String encoding) throws Exception { 28 FileInputStream is = new FileInputStream(fileName) ; 29 return new String (getStreamContentAsBytes(is), encoding) ; 30 } 31 32 static public String getFileContenntAsString(String fileName) throws Exception { 33 FileInputStream is = new FileInputStream(fileName) ; 34 return new String (getStreamContentAsBytes(is)) ; 35 } 36 37 static public byte[] getFileContentAsBytes(String fileName) throws Exception { 38 FileInputStream is = new FileInputStream(fileName) ; 39 return getStreamContentAsBytes(is) ; 40 } 41 42 static public String getStreamContentAsString(InputStream is) throws Exception { 43 char buf[] = new char[is.available()]; 44 BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); 45 in.read(buf); 46 return new String (buf) ; 47 } 48 49 static public byte[] getStreamContentAsBytes(InputStream is) throws Exception { 50 byte buf[] = new byte[is.available()]; 51 for(int start = 0; start < buf.length; start += is.read(buf, start, buf.length - start)); 52 return buf ; 53 } 54 55 static public String getResourceAsString(String resource) throws Exception { 56 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 57 URL url = cl.getResource(resource); 58 InputStream is = url.openStream(); 59 return getStreamContentAsString(is) ; 60 } 61 62 static public byte[] getResourceAsBytes(String resource) throws Exception { 63 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 64 URL url = cl.getResource(resource); 65 InputStream is = url.openStream(); 66 return getStreamContentAsBytes(is) ; 67 } 68 69 static public byte[] serialize(Object obj) throws Exception { 70 ByteArrayOutputStream bytes = new ByteArrayOutputStream() ; 72 ObjectOutputStream out = new ObjectOutputStream(bytes); 73 out.writeObject(obj); 74 out.close(); 75 byte[] ret = bytes.toByteArray() ; 76 return ret ; 78 } 79 80 static public Object deserialize(byte[] bytes) throws Exception { 81 if (bytes == null) return null ; 82 ByteArrayInputStream is = new ByteArrayInputStream(bytes) ; 84 ObjectInputStream in = new ObjectInputStream(is); 85 Object obj = in.readObject() ; 86 in.close(); 87 return obj ; 88 } 89 } | Popular Tags |