An example of writing a potentially large amount of data directly to a zip file, item by item:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
import org.northcoder.titlewebdemo.beans.Title;
import java.util.List;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import org.northcoder.titlewebdemo.util.LoggerUtils;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
*
*/
public class JsonZipFileWriter {
private final List<Title> titles;
private OutputStream out;
public JsonZipFileWriter(List<Title> titles) {
this.titles = titles;
boolean append = true;
try {
this.out = new GZIPOutputStream(
new BufferedOutputStream(
new FileOutputStream(
"E:/TitleWebDemo/foo.zip", append)));
} catch (IOException ex) {
LoggerUtils.LOGGER.error(ex);
}
}
public void write() {
titles.forEach((title) -> {
try {
out.write(title.getBeanDataAsJson().getBytes(UTF_8));
} catch (IOException ex) {
LoggerUtils.LOGGER.error(ex);
}
});
try {
out.close();
} catch (IOException ex) {
LoggerUtils.LOGGER.error(ex);
}
}
}
|