1 4 package org.oddjob.io; 5 6 import java.io.ByteArrayInputStream ; 7 import java.io.ByteArrayOutputStream ; 8 import java.io.IOException ; 9 import java.io.InputStream ; 10 import java.io.OutputStream ; 11 12 24 public class BufferType { 25 26 private final ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 27 28 public Object valueFor(Class required) { 29 if (required == null) { 30 required = OutputStream .class; 31 } 32 if (required.isAssignableFrom(String .class)) { 33 return new String (buffer.toByteArray()); 34 } 35 if (required.isAssignableFrom(InputStream .class)) { 36 return new ByteArrayInputStream (buffer.toByteArray()); 37 } 38 if (required.isAssignableFrom(OutputStream .class)) { 39 return new WrapperOutputStream(); 40 } 41 throw new ClassCastException ("Can not convert from Buffer to " + required); 42 } 43 44 public String toString() { 45 return "Buffer (" + buffer.size() + " bytes)"; 46 } 47 48 public class WrapperOutputStream extends OutputStream { 49 public Object valueFor(Class required) { 50 if (required == null) { 51 throw new ClassCastException ("No default conversion for Buffer contents."); 52 } 53 if (required.isAssignableFrom(String .class)) { 54 return new String (buffer.toByteArray()); 55 } 56 if (required.isAssignableFrom(InputStream .class)) { 57 return new ByteArrayInputStream (buffer.toByteArray()); 58 } 59 throw new ClassCastException ("Can not convert from Buffer contents to " + required); 60 } 61 62 65 public void write(int b) throws IOException { 66 buffer.write(b); 67 } 68 71 public void close() throws IOException { 72 buffer.close(); 73 } 74 77 public void flush() throws IOException { 78 buffer.flush(); 79 } 80 83 public void write(byte[] b) throws IOException { 84 buffer.write(b); 85 } 86 89 public void write(byte[] b, int off, int len) throws IOException { 90 buffer.write(b, off, len); 91 } 92 93 } 94 95 } 96 | Popular Tags |