1 3 package jodd.mail; 4 5 import java.io.ByteArrayInputStream ; 6 import java.io.ByteArrayOutputStream ; 7 import java.io.File ; 8 import java.io.FileInputStream ; 9 import java.io.IOException ; 10 import java.io.InputStream ; 11 import java.io.OutputStream ; 12 import java.io.UnsupportedEncodingException ; 13 14 import javax.activation.DataSource ; 15 import javax.activation.FileTypeMap ; 16 17 23 public class ByteArrayDataSource implements DataSource { 24 25 private byte[] data; private String type; 28 35 public ByteArrayDataSource(File f, String type) throws IOException { 36 this(new FileInputStream (f), type); 37 if (this.type == null) { 38 this.type = FileTypeMap.getDefaultFileTypeMap().getContentType(f); 39 } 40 } 41 42 48 public ByteArrayDataSource(InputStream is, String type) throws IOException { 49 this.type = type; 50 51 ByteArrayOutputStream os = new ByteArrayOutputStream (4096); 52 53 byte buf[] = new byte[4096]; 54 int len; 55 while (true) { 56 len = is.read(buf); 57 if (len < 0) break; 58 os.write(buf, 0, len); 59 } 60 data = os.toByteArray(); 61 } 62 63 69 public ByteArrayDataSource(byte[] data, String type) { 70 this.type = type; 71 this.data = data; 72 } 73 74 82 public ByteArrayDataSource(String data, String type) { 83 this.type = type; 84 try { 85 this.data = data.getBytes("ISO-8859-1"); 86 } catch (UnsupportedEncodingException uex) { 87 } 89 } 90 91 96 public InputStream getInputStream() throws IOException { 97 if (data == null) { 98 throw new IOException ("No data."); 99 } 100 return new ByteArrayInputStream (data); 101 } 102 103 107 public OutputStream getOutputStream() throws IOException { 108 throw new IOException ("getOutputStream() not supported."); 109 } 110 111 116 public String getContentType() { 117 return type; 118 } 119 120 125 public void setContentType(String type) { 126 this.type = type; 127 } 128 129 132 public String getName() { 133 return ""; 134 } 135 136 141 public void writeTo(OutputStream os) throws IOException { 142 os.write(data); 143 } 144 145 150 public byte[] toByteArray() { 151 return data; 152 } 153 154 159 public int getSize() { 160 if (data == null) 161 return -1; 162 else 163 return data.length; 164 } 165 166 173 public String getText() { 174 try { 175 return new String (data, type); 176 } catch (UnsupportedEncodingException uex) { 177 try { 178 return new String (data, "ISO-8859-1"); 179 } catch (UnsupportedEncodingException uex1) { 180 return null; 181 } 182 } 183 } 184 } 185 | Popular Tags |