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?
converting Java Streams to me are really confusing and I do not make them right
The GZIPInputStream
is to be used to decompress an incoming InputStream
. To compress an incoming InputStream
using GZIP, you basically need to write it to a GZIPOutputStream
.
You can get a new InputStream
out of it if you use ByteArrayOutputStream
to write gzipped content to a byte[]
and ByteArrayInputStream
to turn a byte[]
into an InputStream
.
So, basically:
public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
final InputStream zipInputStream;
try {
ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
GZIPOutputStream gzipOutput = new GZIPOutputStream(bytesOutput);
try {
byte[] buffer = new byte[10240];
for (int length = 0; (length = inputStream.read(buffer)) != -1;) {
gzipOutput.write(buffer, 0, length);
}
} finally {
try { inputStream.close(); } catch (IOException ignore) {}
try { gzipOutput.close(); } catch (IOException ignore) {}
}
zipInputStream = new ByteArrayInputStream(bytesOutput.toByteArray());
} catch (IOException e) {
e.printStackTrace();
throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
}
// ...
You can if necessary replace the ByteArrayOutputStream
/ByteArrayInputStream
by a FileOuputStream
/FileInputStream
on a temporary file as created by File#createTempFile()
, especially if those streams can contain large data which might overflow machine's available memory when used concurrently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With