Search code examples
javaswingserializationdata-persistence

Is it possible to store styled text persistently?


So I was trying to serialize some DefaultStyledDocument objects using XMLEncoder. They encode just fine, however when I look at the data, it doesn't encode any actually data, it just gives the class file. I've looked on the internet and saw that many people had trouble with this, but there were no helpful solutions. The best answer I saw was "DefaultStyledDocument isn't a proper bean, so it won't work."

So, is there anyway I can serialize DefaultStyledDocuments, without having to deal with issues between versions? Both binary and text would be acceptable.

Here's some example code of what I want to do:

DefaultStyledDocument content = new DefaultStyledDocument();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(stream);
encoder.writeObject(content);
encoder.close();
stream.toString(); //This is the result of the encoding, which should be able to be decoded to result in the original DefaultStyledDocument

I don't really care if I use XMLEncoder or some other method, it just needs to work.


Solution

  • There's no need to encode Documents using XMLEncoder. EditorKits, part of the Swing Text API, do that job for you. The base level class, EditorKit, has both a read() and write() method. These methods then get extended by various sub-EditorKits to allow the reading and writing of documents. Most documents have their own EditorKits which allows the programmer to read or write the Document.

    However, StyledEditorKit (DefaultStyledDocument's "own" EditorKit) doesn't readily allow reading or writing. You need to use RTFEditorKit, which does support reading and writing. However, Swing's builtin RTFEditorKit does not work very well. So someone designed a free "Advanced" Editor kit available here. In order to write a DefaultStyledDocument with AdvancedRTFEditorKit, using the following code (the variable content is a DefaultStyledDocument).

    AdvancedRTFEditorKit editor = new AdvancedRTFEditorKit();
    Writer writer = new StringWriter();
    editor.write(writer, content, 0, content.getLength());
    writer.close();
    String RTFText = writer.toString();
    

    A similar process can be used to read RTFDocuments with RTFEditorKit's read() method.