java - 将大文本附加到 jtextpane 会导致“OutOfMemoryError : Java heap space”

标签 java swing jtextpane heap-memory

我正在尝试将文件文本附加到我的 JTextPane 中。这对于小于 10Mb 的文件非常有用,但对于大于 10Mb 的文件(我检查了 ~50Mb),我得到了臭名昭著的异常“OutOfMemoryError:Java 堆空间”。

我试图理解,如果两种方法都是静态的,并且 while(line!=null) 下的每次迭代中都没有“new”,为什么我会获得 java 堆内存。如果我可以在常规 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);
}

最佳答案

为什么要为每一行添加属性? Swing 需要做大量工作来跟踪所有这些属性,或者将它们合并为整个文件的一个属性。

将所有数据加载到文本 Pane 后,尝试使用如下代码一次性设置整个文本 Pane 的属性。

SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);

另外,我认为您不需要使用属性来设置字体。您应该能够使用:

textPane.setFont(...);

关于java - 将大文本附加到 jtextpane 会导致“OutOfMemoryError : Java heap space”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051947/

相关文章:

java - 具有 DESC 顺序的 Hibernate 索引

java - 使用 Servlet 来处理 AJAX 请求?

java - 为什么 Player.gamesCompleted 属性永远不会更新?

java - miglayout关于列的问题

java - 获取 JTextComponent 的 HTMLDocument 中的当前偏移量

java - 使用 getStyleDdocument 的超链接不起作用

java - 线程 "main"java.lang.IndexOutOfBoundsException : Index: 0, 中的异常大小:0

java - textArea.setText ("") 不会清除 JTextArea 中的文本

java - 更新 edt 中的 swing 组件

java - JTextPane:setCharacterAttributes 的渲染器是什么?