I have a method like
public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
// a.) create gzip of inputStream
final GZIPInputStream zipInputStream;
try {
zipInputStream = new GZIPInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
}
I wan to convert the inputStream
into zipInputStream
, what is the way to do that?
- The above method is incorrect and throws Exception as "Not a Zip Format"
converting Java Streams to me are really confusing and I do not make them right
The
GZIPInputStream
is to be used to decompress an incomingInputStream
. To compress an incomingInputStream
using GZIP, you basically need to write it to aGZIPOutputStream
.You can get a new
InputStream
out of it if you useByteArrayOutputStream
to write gzipped content to abyte[]
andByteArrayInputStream
to turn abyte[]
into anInputStream
.So, basically:
You can if necessary replace the
ByteArrayOutputStream
/ByteArrayInputStream
by aFileOuputStream
/FileInputStream
on a temporary file as created byFile#createTempFile()
, especially if those streams can contain large data which might overflow machine's available memory when used concurrently.GZIPInputStream is for reading gzip-encoding content.
If your goal is to take a regular input stream and compress it in the GZIP format, then you need to write those bytes to a GZIPOutputStream.
See also this answer to a related question.