It is tedious to send an array of bytes to a ByteArrayOutputStream stream in one method and immediately receive it in a ByteArrayInputStream . I'm trying to do it like this:

 public void rW() { byte[] bytes = { 1, 2, 3, 4 }; byte[] outputArray = new byte[4]; try (OutputStream out = new ByteArrayOutputStream(); InputStream in = new ByteArrayInputStream(out)) // но он требует массив байтов { out.write(bytes); int b; while ((b = in.read(outputArray)) != -1) { System.out.println(b); } System.out.println(Arrays.toString(outputArray)); } catch (IOException e) { e.printStackTrace(); } } 

It turns out that I can not directly put the output object into the input stream designer.
So how can I be here? How do I use the ByteArrayOutputStream and ByteArrayInputStream classes in the same bundle?

    2 answers 2

    Perhaps you are not quite sure how to work with data streams (i / o streams).

    InputStream and OutputStream are abstractions of sequential access (read and write, respectively) to the data stream. A specific implementation still needs to have this data in a specific form.

    ByteArrayOutputStream is an abstraction for writing to a byte array in sequence. It is used to write an arbitrary amount of data into an array and get it ultimately by calling the toByteArray() method.

    ByteArrayInputStream is an abstraction for sequential reading from an array. Naturally, an array is needed for it to be quite specific and tangible, otherwise from where will the stream read the data?

    In general, there are a couple of PipedInputStream/PipedOutputStream streams in PipedInputStream/PipedOutputStream for such purposes PipedInputStream/PipedOutputStream

    PipedOutStream are written to PipedOutStream and extracted from PipedInputStream

    They are specifically designed to communicate in a multi-application.