Alex
Alex

Reputation: 91

Java: OutputStream and InputStream

I have a class CBZip2OutputStream from "apache bzi2 library" , it can transform binary data stream to bzi2 data stream. But I need to archive a string. Therefore, i think, i should create an input stream from that outputstream, write that data to outputstream and read archived data from inputstream... but how to link outputstream and inputstream?

Upvotes: 2

Views: 1076

Answers (3)

Gab
Gab

Reputation: 777

You can use several method to get an InputStream out of an OutputStream.

  • write the data the data into a memory buffer (ByteArrayOutputStream) get the byteArray and read it again with a ByteArrayInputStream. This is the best approach if you're sure your data fits into memory.
  • copy your data to a temporary file and read it back.
  • use pipes: this is the best approach both for memory usage and speed (you can take full advantage of the multi-core processors) and also the standard solution offered by Oracle.
  • use "circular buffers" or pipes trough an external library.

Here is a complete tutorial.

Upvotes: 0

AlexR
AlexR

Reputation: 115328

You can just read from input stream and write to output stream. It is a common practice. IOUtils.copy() (from jakarta commons) does it, so you event do not need to implement the loop.

Alternatively you can use PipedInputStream and PipedOutputStream.

Upvotes: 2

user439793
user439793

Reputation:

First, you probably want a DataOutputStream: it is designed to take primitives and objects and convert them to bytes. It does handle strings as well.

Next, use piped I/O: PipedInputStream and PipedOutputStream. You can use them to link streams together, similar to piping input from one process into another from the command line.

Upvotes: 1

Related Questions