简体   繁体   English

Java 超出 memory 堆空间

[英]Java Out of memory heap space

Acutally i have a problem of java Out of memory heap space with my code below: Acutally 我有一个问题java Out of memory heap space我的代码如下:

It works with medium sized csv files, on the other hand its plant with large csv files, with java out of memory error.它适用于中型 csv 文件,另一方面它的工厂适用于大型 csv 文件,memory 错误中有 java。

Thank you very much for your help:)非常感谢您的帮助:)

package routines;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.*;
import java.util.*;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class RemoveLineBreakFromCsvHelper {
public static void updateCSV (String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);
        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ';');
        List<String[]> csvBody = reader.readAll();
        System.out.println("Read CSV File");
       
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
           
                if(strArray[j].contains("\n")){ //String to be replaced
               
                System.out.println("Remove Line Breaks");
                    csvBody.get(i)[j] = strArray[j].replace("\n".toString(), ". "); //Target replacement
                   
                }
            }
        }
        reader.close();
        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ';');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }
}
List<String[]> csvBody = reader.readAll();

If you're reading a large file, this reads a lot of data.如果您正在读取一个大文件,这会读取大量数据。

Instead, read each row one-by-one, and write them one-by-one:相反,逐行读取每一行,并逐行写入:

String[] strArray;
while ((strArray = reader.readNext()) != null) {
  // ...

  writer.writeNext(strArray);
}

Since you're currently writing to the same file that you're reading from, you'd need to first write to a different file, and then move the new file to overwrite the old one.由于您当前正在写入与正在读取的文件相同的文件,因此您需要先写入另一个文件,然后移动新文件以覆盖旧文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM