0

How to create OutputStream from ByteArrayOutputStream in Java

Taranfx
  • 10,273
  • 15
  • 75
  • 95

4 Answers4

5

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
  • 57,133
  • 30
  • 158
  • 207
4

ByteArrayOutputStream is a subclass of OutputStream.

ByteArrayOutputStream bos = ...;
OutputStream os = bos;
Oak Bytes
  • 4,489
  • 4
  • 34
  • 52
  • Im getting class cast exception in android when I do this :D – Taranfx May 04 '11 at 05:40
  • 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
1

A ByteArrayOutputStream is an OutputStream. I.e. you can just assign it like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream out = baos;
WhiteFang34
  • 68,826
  • 17
  • 104
  • 110
  • Reverse? What are you talking about? – WhiteFang34 May 04 '11 at 06:35
  • 1
    I 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
-2

You can create a helper method like follows:

public OutputStream convert(ByteArrayOutputStream arrayOutputStreamParam){
        return arrayOutputStreamParam;
    }
Koekiebox
  • 5,551
  • 13
  • 51
  • 87