为什么我出现内存不足错误

时间:2017-04-06 11:51:58

标签: java

我一直在这个文件上收到OutOfMemory错误,我不知道为什么。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class Sgrep {

    private String name;
    public String field2;
    public String go;
    File File;
    public String end;

    Sgrep(String File0, String first) {
        go = File0;
        File = new File(File0);
        name = first;
    }

    public String getFilename() {
        return go;
    }

    public String search() {
        try {
            if (name == null) {
                System.out.println("You cannot give a null string.");
            }

            BufferedReader yo = new BufferedReader(new FileReader(File));

            StringBuffer bruh = new StringBuffer();
            String line = null;
            while ((line = yo.readLine()) != null) {
                while (line.indexOf(name) > 0) {
                    bruh.append(line); // here is the first error
                }

                yo.close();
                end = bruh.toString();
            }
        } catch (FileNotFoundException e) {
            return name + "There is a FileNotFoundExcpetion error. This could happen for various reasons, such as the file not being there, or else being read protected from you, or for example being a directory rather than a file.";
        } catch (Exception e) {
            return "You have an io exeption.";
        }
        return end;
    }
}

并在此

public class TesterClass{
    public static void main(String[] args){
    if(args.length != 2){

    System.out.println("Usage: java Sgrep <string> <filename>");
    return;

    }
    Sgrep task = new Sgrep(args[0],args[1]); 
    System.out.println(task.getFilename());
    System.out.println(task.search()); // here is the error

    }
}

我认为第二个错误是因为第一个程序。它说错误是

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
    at java.lang.AbstractStringBuilder.append(Unknown Source)
    at java.lang.StringBuffer.append(Unknown Source)
    at Sgrep.search(Sgrep.java:35)
    at TesterClass.main(TesterClass.java:12)

有谁知道这是为什么?

1 个答案:

答案 0 :(得分:6)

此循环会一次又一次地向String添加相同的StringBuffer(假设条件为true),直到内存不足为止:

while (line.indexOf(name) > 0)
{
    bruh.append(line); // here is the first error
}

将其更改为

if (line.indexOf(name) > 0)
{
    bruh.append(line);
}

只需添加一次。