试图在大文件中查找单词。文件逐行读取。读取redLine异常的方式时抛出。有没有办法解决这个问题?你可以在地板上看到它作为一个字符串?读取文件java.lang.OutOfMemoryError
for(String line; (line = fileOut.readLine()) != null;){
if(line.contains(commandString))
System.out.println(count + ": " + line);
count++;
}
java.lang.OutOfMemoryError:
UDP:
这是我所有的坏代码:
static String file = "files.txt";
static String commandString = "first";
static int count = 1;
public static void main(String[] args) throws IOException
{
try(BufferedReader fileOut = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1251"))){
for(String line; (line = fileOut.readLine()) != null;){
if(line.contains(commandString))
System.out.println(count + ": " + line);
count++;
}
System.out.println("before wr close :" + Runtime.getRuntime().freeMemory());
fileOut.close();
}catch(Exception e) {
System.out.println(e);
}
}
这不应该是'for'循环。但无论如何,'fileOut'是什么,它是如何定义和打开的?该文件来自哪里,你确定它被正确地分解成行而不是数据/二进制文件? – RealSkeptic 2015-02-08 20:32:57
您应该向我们展示堆栈跟踪以及与发生错误的行相关的支持代码。您提供的循环显示行字段被重复覆盖,这不会导致OOM。 – MarsAtomic 2015-02-08 20:33:26
为什么在找到commandString时不打破for循环? – 2015-02-08 20:37:12