簡體   English   中英

如何使用PrintWriter克服內存不足異常?

[英]How to overcome out of memory exception with PrintWriter?

下面的代碼讀取一堆.csv文件,然后將它們組合成一個.csv文件。 我嘗試了system.out.println ...所有數據點都是正確的,但是當我嘗試使用PrintWriter我得到了:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

我嘗試使用FileWriter但遇到了相同的錯誤。 我應該如何更正我的代碼?

public class CombineCsv {
    public static void main(String[] args) throws IOException {
        PrintWriter output  = new PrintWriter("C:\\User\\result.csv");
        final File file = new File("C:\\Users\\is");
        int i = 0;
        for (final File child: file.listFiles()) {
            BufferedReader CSVFile = new BufferedReader( new FileReader( "C:\\Users\\is\\"+child.getName()));
            String dataRow = CSVFile.readLine(); 
            while (dataRow != null) {
                String[] dataArray = dataRow.split(",");
                for (String item:dataArray) { 
                    System.out.println(item + "\t");
                    output.append(item+","+child.getName().replaceAll(".csv", "")+",");
                    i++;
                }
                dataRow = CSVFile.readLine(); // Read next line of data.
            } // Close the file once all data has been read.
            CSVFile.close();
        } 
        output.close();
        System.out.println(i);
    } 
}

我只能想到兩種可能導致該代碼導致OOME的情況:

  • 如果file目錄中包含大量元素,則file.listFiles()可以創建大量File對象數組。

  • 如果輸入文件之一包含很長的一行,則CSVFile.readLine()在讀取過程中可能會占用大量內存。 (最多為該行中字節數的6倍。)

解決這兩個問題的最簡單方法是使用-Xmx JVM選項增加Java堆大小。


我看不出有任何原因導致您使用PrintWriter

嘗試

boolean autoFlush = true; PrintWriter output = new PrintWriter(myFileName, autoFlush);

它創建一個PrintWriter實例,每次有新行或新格式時都會刷新內容。

暫無
暫無

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

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