Edmon
Edmon

Reputation: 4872

Compressing content in Java without file I/O

I would like to perform repeated compression task for CPU profiling without doing any file I/O but strictly reading a byte stream. I want to do this in Java (target of my benchmark).

Does anyone have a suggestion how to do this? I used Zip API that uses ZipEntry but ZipEntry triggers file I/O.

Any suggestions or code samples are highly appreciated.

Upvotes: 3

Views: 165

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503649

I used Zip API that uses ZipEntry but ZipEntry triggers file I/O.

I wouldn't expect it to if you use a ByteArrayOutputStream as the underlying output:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(baos);
... write to zipStream ...

Likewise wrap your byte array for reading data from in a ByteArrayInputStream.

Of course, ZipOutputStream is appropriate if you want to create content using the zip compression format, which is good for (or at least handles :) multiple files. For a single stream of data, you may want to use DeflaterOutputStream or GZIPOutputStream, again using a ByteArrayOutputStream as the underlying output.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533870

Instead of using a FileInputStream or FileOutputStream you can use ByteArrayInputStream and ByteArrayOutputStream.

Upvotes: 1

Related Questions