How to create OutputStream from ByteArrayOutputStream in Java
Asked
Active
Viewed 1.9k times
4 Answers
6
Following runs without error:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStream outStream = stream;
If you see the docs for ByteArrayOutputStream you will find that it extends OutputStream.

Harry Joy
- 58,650
- 30
- 162
- 207
-
1
-
-
you don't even need the intermediate stream variable. `OutputStream outStream = new ByteArrayOutputStream();` – рüффп Jul 09 '22 at 00:17
4
ByteArrayOutputStream
is a subclass of OutputStream
.
ByteArrayOutputStream bos = ...;
OutputStream os = bos;

Oak Bytes
- 4,649
- 4
- 36
- 53
-
-
You shouldn't be. In fact assume you have control of the object, you should be doing OutputStream os=new ByteArrayOutputStream() to begin with.... – MJB May 04 '11 at 05:56
-
I get OutputStream from a ContentProvider, its not actually in my control. – Taranfx May 04 '11 at 06:31
-
@taranfx There will only be a ClassCastException if a cast is done. There is no cast in my example code. As MJB says, there is likely no need to deal with a ByteArrayOutputStream type directly as OutputStream contains all the relevant nominative type information. – May 05 '11 at 00:38
2
A ByteArrayOutputStream
is an OutputStream
. I.e. you can just assign it like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream out = baos;

WhiteFang34
- 70,765
- 18
- 106
- 111
-
-
1I imagine that he wants a BAOS from an OutputStream ( which has been obtained from something like HttpUrlConnection.getOutputStream() ) which is also the situation i am in! – Dori Jun 24 '11 at 09:54
-3
You can create a helper method like follows:
public OutputStream convert(ByteArrayOutputStream arrayOutputStreamParam){
return arrayOutputStreamParam;
}

Koekiebox
- 5,793
- 14
- 53
- 88
-
It's useless as the ByteArrayOutputStream is an implementation of the OutputStream Interface, see the accepted answer. – рüффп Jul 09 '22 at 00:19