簡體   English   中英

用Java編寫多個文件的最快方法

[英]Fastest way to write multiple files in java

我有需要將多個輸入流寫入Java中的臨時文件的要求。 我有以下邏輯代碼段。 有沒有更好的方法可以有效地做到這一點?

final String tempZipFileName = "log" + "_" + System.currentTimeMillis();
        File tempFile = File.createTempFile(tempZipFileName, "zip");
        final FileOutputStream oswriter = new FileOutputStream(tempFile);
        for (final InputStream inputStream : readerSuppliers) {
            byte[] buffer = new byte[102400];
            int bytesRead = 0;

            while ((bytesRead = inputStream.read(buffer)) > 0) {
                oswriter.write(buffer, 0, bytesRead);
            }
            buffer = null;
            oswriter.write(System.getProperty("line.separator").getBytes());
            inputStream.close();
        }

我有多個文件,大小從45到400 mb不等,對於典型的45 mb和360 mb文件,此方法平均需要3分鍾左右。 可以進一步改善嗎?

您可以嘗試BufferedInputStream

正如@StephenC回答的那樣,在這種情況下使用BufferedInputStream是無關緊要的,因為緩沖區足夠大。

我在計算機(帶有SSD驅動器)上重現了該行為。 我拿了一個100MB的文件。

  • 通過此示例創建新文件花了110毫秒。
  • 使用InputStreamBuffer和OutputStream = 120 ms。
  • 使用InputStream和OutputStreamBuffer = 120 ms。
  • 使用InputStreamBuffer和OutputStreamBuffer = 110 ms。

我沒有你那么長的執行時間。

也許問題來自您的readerSuppliers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM