![](/img/trans.png)
[英]What is the root cause of getting Out Of Memory Exception? How can we overcome this?
[英]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.