Java 为什么我会出现内存不足错误
我一直在这个文件上得到一个OutOfMemory错误,我不知道为什么Java 为什么我会出现内存不足错误,java,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;
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
}
}
有人知道这是为什么吗?此循环将一次又一次地将相同的
字符串添加到StringBuffer
(假设条件为true
),直到内存耗尽:
while (line.indexOf(name) > 0)
{
bruh.append(line); // here is the first error
}
换成
if (line.indexOf(name) > 0)
{
bruh.append(line);
}
以便只添加一次。可能重复的
if (line.indexOf(name) > 0)
{
bruh.append(line);
}