-1

I keep getting an OutOfMemory error on this file and I dont know why.

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;
    }
}

and on this

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

    }
}

I assume the second error is because of the first program. It says that the error is

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)

Does anyone know why this is?

Jens
  • 20,533
  • 11
  • 60
  • 86
CCgaMer
  • 39
  • 3
  • 2
    Possible duplicate of [java.lang.OutOfMemoryError: Java heap space](http://stackoverflow.com/questions/1596009/java-lang-outofmemoryerror-java-heap-space) – Michael Apr 06 '17 at 11:53

1 Answers1

6

This loop will add the same String to your StringBuffer again and again (assuming the condition is true) until you run out of memory :

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

change it to

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

in order to add it just once.

Eran
  • 387,369
  • 54
  • 702
  • 768