我想要一个文件的文本追加到我的JTextPane。这对于10Mb以下的文件非常适用,但对于大小超过它的文件(我检查了〜50Mb),我得到了臭名昭着的异常'OutOfMemoryError:Java heap space'。追加大的文本中“的OutOfMemoryError到的JTextPane结果:Java堆空间
我试图理解为什么会出现Java堆内存,如果这两种方法都是静态的,下的,而每一次迭代就没有“新”(线!= NULL)。如果我可以在常规的txt编辑器中打开该文件,为什么此代码无法执行?
的代码看起来是这样的:
public static void appendFileData(JTextPane tPane, File file) throws Exception
{
try{
//read file's data
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
try{
while (line != null)
{
JTextPaneUtil.appendToConsole(tPane, "\n"+line,Color.WHITE, "Verdana", 14);
line = br.readLine();
}
}finally
{
br.close();
}
}catch(Exception exp)
{
throw exp;
}
}
的appendToConsole是:
public static void appendToConsole(JTextPane console, String userText, Color color, String fontName, int fontSize)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, fontName);
aset = sc.addAttribute(aset, StyleConstants.FontSize, fontSize);
aset = sc.addAttribute(aset,StyleConstants.Alignment, StyleConstants.ALIGN_CENTER);
int len = console.getDocument().getLength();
console.setCaretPosition(len);
console.setCharacterAttributes(aset, false);
console.replaceSelection(userText);
}
这可能是因为你的文件是不是有一个换行符(如:二进制可执行文件) – Chris