RTFEditorKit 读()/写()错误?

RTFEditorKit read()/write() bug?

考虑以下代码:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;


public class TestRTF  {
    public static void main(String args[]) throws BadLocationException, IOException {
        new TestRTF();
    }

    public TestRTF() throws BadLocationException, IOException {
        StyledDocument doc = new DefaultStyledDocument();
        JTextPane tp = new JTextPane(doc);
        doc.insertString(0, "This is a test", null);
        RTFEditorKit kit = new RTFEditorKit();
        for(int i=0; i<4; i++) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            kit.write(out, doc, 0, doc.getLength());
            String s = out.toString();
            System.out.println(s);
            System.out.println("-------------------");
            doc.remove(0, doc.getLength());
            kit.read(new ByteArrayInputStream(s.getBytes()), doc, 0);
        }        
    }
}

我希望这会打印出相同的字符串四次,但不是在从 TextPane 读取的循环中,并将内容替换为读取的内容导致创建额外的段落:

{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}

\f1\fs24\i0\b0\cf1 This is a test\par
}

-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}

\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\li0\ri0\fi0\ul0\par
}

-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}

\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\par
\ul0\par
}

-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}

\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\par
\par
\ul0\par
}

-------------------

这是 RTFEditorKit 中的错误,还是我做错了什么?

我会说这是 RTFEditorKIt 中的错误。

实际上是空的DefaultStyledDocument(在工具包内部使用)直到最后有一段(有一个\n)。看起来该工具包不关心段落,而是每次都创建新段落而不是使用现有段落。

你可以试试the alternative RTF Editor Kit,它支持更多的东西