1
我需要在5秒內創建100mb的壓縮文件,其中包含使用java的CSV文件。我已經創建了包含CSV文件的test.zip,但它花費了太多的時間(〜30秒)來生成zip文件。這裏是我到目前爲止已經編寫的代碼:Java創建100MB壓縮的csv文件性能問題
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庫。你能幫我麼?
你確定你的機器可以做到嗎? Cna你從命令行嘗試相同的東西。順便說一句''mb' ='milli-bits','MB' ='Mega-Bytes' –
而不是建立一個字符串列表,爲什麼不直接寫入ZipOutputStream呢?這會爲你節省很多時間。 –
當您對CPU進行配置時,您看到什麼並花費最多時間? –