为什么将文件读入内存是Java中内存的4倍?
我有以下代码,它读取以下文件,在每行末尾附加\r\n,并将结果放在字符串缓冲区中:
public InputStream getInputStream() throws Exception {
StringBuffer holder = new StringBuffer();
try{
FileInputStream reader = new FileInputStream(inputPath);
BufferedReader br = new BufferedReader(new InputStreamReader(reader));
String strLine;
//Read File Line By Line
boolean start = true;
while ((strLine = br.readLine()) != null) {
if( !start )
holder.append("\r\n");
holder.append(strLine);
start = false;
}
//Close the input stream
reader.close();
}catch (Throwable e){//this is where the heap error is caught up to 2Gb
System.err.println("Error: " + e.getMessage());
}
return new StringBufferInputStream(holder.toString());
}
我尝试读取一个400Mb的文件,并将最大堆空间更改为2Gb,但它仍然给出了内存不足的堆异常。有什么想法吗?