2017-04-06 50 views
-1

我不斷收到這個文件的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) 

有沒有人知道這是爲什麼?

+2

[java.lang.OutOfMemoryError:Java heap space]的可能重複(http://stackoverflow.com/questions/1596009/java-lang-outofmemoryerror-java-heap-space) – Michael

回答

6

這個循環將一再添加相同StringStringBuffer(假設條件是true),直到耗盡內存:

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

改變它

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

爲了只需添加一次。