【问题标题】:Is it possible to store styled text persistently?是否可以持久存储样式文本?
【发布时间】:2015-03-22 15:31:17
【问题描述】:

所以我尝试使用XMLEncoder 序列化一些DefaultStyledDocument 对象。它们编码得很好,但是当我查看数据时,它并没有对任何实际数据进行编码,它只是给出了类文件。我在互联网上查看过,看到很多人都遇到了这个问题,但没有有用的解决方案。我看到的最佳答案是“DefaultStyledDocument 不是一个合适的 bean,所以它不起作用。”

那么,我是否可以序列化 DefaultStyledDocuments,而不必处理版本之间的问题?二进制和文本都可以接受。

这是我想做的一些示例代码:

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

我真的不在乎我是否使用 XMLEncoder 或其他方法,它只需要工作。

【问题讨论】:

    标签: java swing serialization data-persistence


    【解决方案1】:

    无需使用 XMLEncoder 对文档进行编码。 EditorKits 是 Swing Text API 的一部分,可以为您完成这项工作。基级类 EditorKit 具有 read()write() 方法。然后,这些方法被各种 sub-EditorKits 扩展以允许读取和写入文档。大多数文档都有自己的 EditorKit,允许程序员读取或写入文档。

    但是,StyledEditorKit(DefaultStyledDocument 的“自己的”EditorKit)不允许读取或写入。您需要使用支持读写的 RTFEditorKit。然而,Swing 的内置 RTFEditorKit 并不能很好地工作。所以有人设计了一个免费的“高级”编辑器工具包here。为了使用 AdvancedRTFEditorKit 编写 DefaultStyledDocument,请使用以下代码(变量 content 是 DefaultStyledDocument)。

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

    使用 RTFEditorKit 的 read() 方法可以使用类似的过程来读取 RTFDocuments。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多