Is it possible to store styled text persistently?

为君一笑 提交于 2020-01-07 04:23:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29196207/is-it-possible-to-store-styled-text-persistently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!