【发布时间】:2015-09-15 07:21:28
【问题描述】:
我需要在 5 秒内创建 100mb 压缩文件,其中包含使用 java 的 CSV 文件。我创建了包含 CSV 文件的 test.zip,但生成 zip 文件需要太多时间(约 30 秒)。这是我到目前为止编写的代码:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/* Create instance of ZipOutputStream to create ZIP file. */
ZipOutputStream zipOutputStream = new ZipOutputStream(baos);
/* Create ZIP entry for file.The file which is created put into the
* zip file.File is not on the disk, csvFileName indicates only the
* file name to be put into the zip
*/
ZipEntry zipEntry = new ZipEntry("Test.zip");
zipOutputStream.putNextEntry(zipEntry);
/* Create OutputStreamWriter for CSV. There is no need for staging
* the CSV on filesystem . Directly write bytes to the output stream.
*/
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(zipOutputStream, "UTF-8"));
CsvListWriter csvListWriter = new CsvListWriter(bufferedWriter, CsvPreference.EXCEL_PREFERENCE);
/* Write the CSV header to the generated CSV file. */
csvListWriter.writeHeader(CSVGeneratorConstant.CSV_HEADERS);
/* Logic to Write the content to CSV */
long startTime = System.currentTimeMillis();
for (int rowIdx = 0; rowIdx < 7000000; rowIdx++) {
final List<String> rowContent = new LinkedList<String>();
for (int colIdx = 0; colIdx < 6; colIdx++) {
String str = "R" + rowIdx + "C" + colIdx + " FieldContent";
rowContent.add(str);
}
csvListWriter.write(rowContent);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("time==" + elapsedTime / 1000f + "Seconds");
System.out.println("Size=====" + baos.size() / (Math.pow(1024, 2)) + "MB");
csvListWriter.close();
bufferedWriter.close();
zipOutputStream.close();
baos.close();
我正在使用超级 csv 库,但我也尝试在没有超级 csv 库的情况下在内存中创建 zip 文件,但没有成功。你能帮帮我吗?
【问题讨论】:
-
你确定你的机器可以做到这一点吗? Cna 你从命令行尝试同样的事情。顺便说一句
mb=milli-bits,MB=Mega-Bytes -
与其建立一个字符串列表,为什么不直接写入 ZipOutputStream 呢?这将为您节省不少时间。
-
当您对此进行 CPU 分析时,您看到了什么并花费了最多时间?
-
旁注:使用 try-with-resources 关闭您的流。
-
为什么不直接写入目标文件而不是建立
ByteArrayOutputStream,?你只是在浪费时间和空间。
标签: java supercsv zipoutputstream