ByteArrayDataSourcepublic class ByteArrayDataSource extends Object implements DataSourceA DataSource backed by a byte array. The byte array may be
passed in directly, or may be initialized from an InputStream
or a String. |
Fields Summary |
---|
private byte[] | data | private int | len | private String | type | private String | name |
Constructors Summary |
---|
public ByteArrayDataSource(InputStream is, String type)Create a ByteArrayDataSource with data from the
specified InputStream and with the specified MIME type.
The InputStream is read completely and the data is
stored in a byte array.
DSByteArrayOutputStream os = new DSByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while ((len = is.read(buf)) > 0)
os.write(buf, 0, len);
this.data = os.getBuf();
this.len = os.getCount();
/*
* ByteArrayOutputStream doubles the size of the buffer every time
* it needs to expand, which can waste a lot of memory in the worst
* case with large buffers. Check how much is wasted here and if
* it's too much, copy the data into a new buffer and allow the
* old buffer to be garbage collected.
*/
if (this.data.length - this.len > 256*1024) {
this.data = os.toByteArray();
this.len = this.data.length; // should be the same
}
this.type = type;
| public ByteArrayDataSource(byte[] data, String type)Create a ByteArrayDataSource with data from the
specified byte array and with the specified MIME type.
this.data = data;
this.type = type;
| public ByteArrayDataSource(String data, String type)Create a ByteArrayDataSource with data from the
specified String and with the specified MIME type.
The MIME type should include a charset
parameter specifying the charset to be used for the
string. If the parameter is not included, the
default charset is used.
String charset = null;
try {
ContentType ct = new ContentType(type);
charset = ct.getParameter("charset");
} catch (ParseException pex) {
// ignore parse error
}
if (charset == null)
charset = MimeUtility.getDefaultJavaCharset();
// XXX - could convert to bytes on demand rather than copying here
this.data = data.getBytes(charset);
this.type = type;
|
Methods Summary |
---|
public java.lang.String | getContentType()Get the MIME content type of the data.
return type;
| public java.io.InputStream | getInputStream()Return an InputStream for the data.
Note that a new stream is returned each time
this method is called.
if (data == null)
throw new IOException("no data");
if (len < 0)
len = data.length;
return new SharedByteArrayInputStream(data, 0, len);
| public java.lang.String | getName()Get the name of the data.
By default, an empty string ("") is returned.
return name;
| public java.io.OutputStream | getOutputStream()Return an OutputStream for the data.
Writing the data is not supported; an IOException
is always thrown.
throw new IOException("cannot do this");
| public void | setName(java.lang.String name)Set the name of the data.
this.name = name;
|
|