我正在尝试预处理一个大的txt文件(10G),并将其存储在二进制文件中以供将来使用。当代码运行时,它会变慢并以
结束Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
输入文件具有以下结构
200020000000008;0;2
200020000000004;0;2
200020000000002;0;2
200020000000007;1;2
这是我正在使用的代码:
String strLine;
FileInputStream fstream = new FileInputStream(args[0]);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
//Read File Line By Line
HMbicnt map = new HMbicnt("-1");
ObjectOutputStream outputStream = null;
outputStream = new ObjectOutputStream(new FileOutputStream(args[1]));
int sepIndex = 15;
int sepIndex2 = 0;
String str_i = "";
String bb = "";
String bbBlock = "init";
int cnt = 0;
lineCnt = 0;
while ((strLine = br.readLine()) != null) {
//rozparsovat radek
str_i = strLine.substring(0, sepIndex);
sepIndex2 = strLine.substring(sepIndex+1).indexOf(';');
bb = strLine.substring(sepIndex+1, sepIndex+1+sepIndex2);
cnt = Integer.parseInt(strLine.substring(sepIndex+1+sepIndex2+1));
if(!bb.equals(bbBlock)){
outputStream.writeObject(map);
outputStream.flush();
map = new HMbicnt(bb);
map.addNew(str_i + ";" + bb, cnt);
bbBlock = bb;
}
else{
map.addNew(str_i + ";" + bb, cnt);
}
}
outputStream.writeObject(map);
//Close the input stream
br.close();
outputStream.writeObject(map = null);
outputStream.close();
基本上,它会遍历 in 文件并将数据存储到对象 HMbicnt(这是一个 HashMap )。一旦在第二列中遇到新值,它应该将对象写入输出文件,释放内存并继续。
感谢您的帮助。
最佳答案
我认为问题不在于内存中有10G,而在于你创建了太多的HashMap。也许您可以清除 HashMap,而不是在不再需要它后重新创建它。 java.lang.OutOfMemoryError: GC overhead limit exceeded中似乎也有类似的问题,这也是关于HashMap的
关于Java GC 开销超出限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172013/