Search code examples
javartfjtextpane

RTFEditorKit read()/write() bug?


consider the following code:

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);
        }        
    }
}

I would expect this to print out the same string four times, but instead in the cycle of reading from the TextPane, and replacing the content with what was read results in additional paragraph being created:

{\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
}

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

Is this a bug in the RTFEditorKit, or am I doing something wrong?


Solution

  • I would say it's bug in RTFEditorKIt.

    Actually empty DefaultStyledDocument (which is used in the kit internlly) till has one paragraph (with one \n) in the end. Looks like the kit don't care about the paragraph but creates new ones every time rather than using existing.

    You can try the alternative RTF Editor Kit which supports much more things