java - Why am I getting an out of Memory error -


i keep getting outofmemory error on file , 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 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 first error                 }                  yo.close();                 end = bruh.tostring();             }         } catch (filenotfoundexception e) {             return name + "there filenotfoundexcpetion error. happen various reasons, such file not being there, or else being read protected you, or example being directory rather file.";         } catch (exception e) {             return "you have 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 error      } } 

i assume second error because of first program. says error

exception in thread "main" java.lang.outofmemoryerror: java heap space     @ java.util.arrays.copyof(unknown source)     @ java.lang.abstractstringbuilder.ensurecapacityinternal(unknown source)     @ java.lang.abstractstringbuilder.append(unknown source)     @ java.lang.stringbuffer.append(unknown source)     @ sgrep.search(sgrep.java:35)     @ testerclass.main(testerclass.java:12) 

does know why is?

this loop add same string stringbuffer again , again (assuming condition true) until run out of memory :

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

change to

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

in order add once.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -