[英]java.lang.OutOfMemoryError: GC overhead limit exceeded when reading large PDF file using itext PdfReader
[英]java.lang.OutOfMemoryError: GC overhead limit exceeded while Reading a Large Text file
我有一个文本文件,大小约为2 GB。 文件的每一行具有以下格式:
一些可能用逗号分隔的文本,唯一整数
我需要将每一行分成两部分:文本,唯一整数并将其作为键值对放入Hashmap中。
现在,即使堆大小设置为10 GB,我也面临OutOfMemory错误。
可能有两个原因:1.我读取文件的方式错误。 2.我创建了太多不必要的String对象。
这就是我在做什么:
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.txt");
InputStreamReader stream = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(stream);
while(true)
{
line =reader.readLine();
if (line == null) {
break;
}
String text= line.substring(0, line.lastIndexOf(",")).trim();
String id = line.substring(line.lastIndexOf(",") + 1).trim();
//put this in a hashmap and other processing
}
由于我需要将文本的每一行分成两部分,并且第一部分(文本)也可能有逗号,因此我为此使用了substring()方法。
我使用trim的原因是我需要将文本和id放在Hashmap中,而不能在末尾加上前导空格。
错误信息:
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.util.Arrays.copyOfRange(Arrays.java:3664)
at java.lang.String.<init>(String.java:207)
at java.lang.String.substring(String.java:1969)
你应该添加循环条件。 请使用下划线代码再试一次。它似乎可以正常工作!
try {
String line;
while ((line = reader.readLine()) != null) {
String text = line.substring(0, line.lastIndexOf(",")).trim();
String id = line.substring(line.lastIndexOf(",") + 1).trim();
//put this in a hashmap and other processing
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.