[英]How to create a GZIP file in Java from another file without creating a new physical file
I was working with this example:我正在处理这个例子:
public class GZipExample {
public static void main(String[] args) {
// compress a file
Path source = Paths.get("/home/test/sitemap.xml");
Path target = Paths.get("/home/test/sitemap.xml.gz");
if (Files.notExists(source)) {
System.err.printf("The path %s doesn't exist!", source);
return;
}
try {
GZipExample.compressGzip(source, target);
} catch (IOException e) {
e.printStackTrace();
}
}
// copy file (FileInputStream) to GZIPOutputStream
public static void compressGzip(Path source, Path target) throws IOException {
try (GZIPOutputStream gos = new GZIPOutputStream(
new FileOutputStream(target.toFile()));
FileInputStream fis = new FileInputStream(source.toFile())) {
// copy file
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
gos.write(buffer, 0, len);
}
}
}
I would like only to create the gzip file in memory and not physically on disk.我只想在内存中创建 gzip 文件,而不是在磁盘上物理创建。 I'm not sure if that is possible using some kind of stream or in-memory file?我不确定是否可以使用某种流或内存文件?
You can write to any OutputStream
you want, meaning that it does not need to be a FileOutputStream
.您可以写入任何所需的OutputStream
,这意味着它不需要是FileOutputStream
。 You can use a ByteArrayOutputStream
instead:您可以改用ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gos = new GZIPOutputStream(baos);
FileInputStream fis = new FileInputStream(source.toFile())) {
// copy file
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
gos.write(buffer, 0, len);
}
}
byte[] data = baos.toByteArray();
The gzipped data is now a byte[]
in your memory.压缩后的数据现在是您记忆中的一个byte[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.