How can I convert an OutputStream to a byte array? I have found that first I need to convert this OutputStream to a ByteArrayOutputStream. There is only write() method in this OutputStream class and I don't know what to do. Is there any idea?
-
Use toByteArray to extract the bytesDeepak Bala– Deepak Bala2014-04-18 12:25:26 +00:00Commented Apr 18, 2014 at 12:25
-
2Strictly speaking, you can't. An output stream is an output stream is an output stream. Once it exists, you could maybe wrap it in a PrintStream or something.Ingo– Ingo2014-04-18 12:28:47 +00:00Commented Apr 18, 2014 at 12:28
5 Answers
Create a ByteArrayOutputStream.
Grab its content by calling toByteArray()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.writeTo(myOutputStream);
baos.toByteArray();
3 Comments
ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.writeTo(myOutputStream); baos.toByteArray();baos.toString() compared to baos.toByteArray()? I have used it first on some old projects but for some reason, I was not able to generate an SHA-1 hash digest from it but was working fine for the second one and still I have no clue why may be something in the reading file.If the OutputStream object supplied is not already a ByteArrayOutputStream, one can wrap it inside a delegate class that will "grab" the bytes supplied to the write() methods, e.g.
public class DrainableOutputStream extends FilterOutputStream {
private final ByteArrayOutputStream buffer;
public DrainableOutputStream(OutputStream out) {
super(out);
this.buffer = new ByteArrayOutputStream();
}
@Override
public void write(byte b[]) throws IOException {
this.buffer.write(b);
super.write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
this.buffer.write(b, off, len);
super.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
super.write(b);
}
public byte[] toByteArray() {
return this.buffer.toByteArray();
}
}
To reduce the overhead, the calls to super in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired.
A more detailed discussion can be found in another StackOverflow question.
Comments
You need to do 2 things
- Using ByteArrayOutputStream write to it
- Using toByteArray(), you will get the contents as byte[]
You could even extend it as mentioned here
Comments
If You try ByteArrayOutputStream bos=(ByteArrayOutputStream)outputStream then throw ClassCastException.
I did it when I get OutputStream from HttpServletResponse and it is CoyoteOutputStream.(You can create file so dont create file temp).
You can use Java Reflection to convert OutputStream to byte[]:
byte[] bytes = this.getBytes(outStream);
/**
* Get byte from OutputStream
*
* @param outStream
* @return
*/
@SneakyThrows
private byte[] getBytes(OutputStream outStream) {
OutputBuffer outputBuffer = (OutputBuffer) this.getValueByName("ob", outStream);
ByteBuffer byteBuffer = (ByteBuffer) this.getValueByName("bb", outputBuffer);
return (byte[]) this.getValueByName("hb", byteBuffer);
}
/**
* Get value from property
*
* @param name
* @param value
* @return
*/
@SneakyThrows
@SuppressWarnings("unchecked")
private Object getValueByName(String name, Object value) {
List<Field> listFiled = new ArrayList<>();
if (value.getClass().getSuperclass() != null) {
listFiled.addAll(Arrays.asList(value.getClass().getSuperclass().getDeclaredFields()));
}
listFiled.addAll(Arrays.asList(value.getClass().getDeclaredFields()));
Optional<Field> fieldOb = listFiled.stream()
.filter(field -> StringUtils.equalsAnyIgnoreCase(name, field.getName()))
.findFirst();
if (fieldOb.isPresent()) {
Field field = fieldOb.get();
field.setAccessible(true);
return field.get(value);
}
return StringUtils.EMPTY; // FIXME
}