我有一种方法
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);
}我想把inputStream转换成zipInputStream,怎么做呢?
将Java流转换给我是非常令人困惑的,而且我没有纠正它们
发布于 2012-09-07 16:42:46
GZIPInputStream将用于解压缩(传入的InputStream )。要使用GZIP压缩传入的InputStream,基本上需要将其写入GZIPOutputStream。
如果使用InputStream将gzipped内容写入byte[],使用ByteArrayInputStream将byte[]转换为InputStream,则可以从中获得一个新的byte[]。
所以,基本上:
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);
}
// ...如果有必要,可以将ByteArrayOutputStream/ByteArrayInputStream替换为由File#createTempFile()创建的临时文件上的FileOuputStream/FileInputStream,特别是如果这些流可以包含大型数据,当并发使用时可能会溢出机器的可用内存。
发布于 2012-09-07 16:36:26
https://stackoverflow.com/questions/12322073
复制相似问题