Serialize;用对象序列化可以吗?

解决方案 »

  1.   

    Following program loads an RTF file in startup, and saves the RTF file when closing. It uses JTextPane and DefaultStyledDocument. However, whenever the file is being read, there's an extra new line character inserted to the JTextPane. Don't know why. For example, when saving, I can see there are 18 characters saved in the document, but when I read, it becomes 19! It is using standard way to read and write the file, very straightforward.import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.text.rtf.*;
    import javax.swing.undo.*;public class TestFrame extends JFrame {
    protected JTextPane m_monitor;
    protected StyleContext m_context;
    protected DefaultStyledDocument m_doc;
    protected RTFEditorKit m_kit;public TestFrame() {
    setSize(600, 400);m_monitor = new JTextPane();
    m_kit = new RTFEditorKit();
    m_monitor.setEditorKit(m_kit);
    m_context = new StyleContext();
    m_doc = new DefaultStyledDocument(m_context);
    m_monitor.setDocument(m_doc);JScrollPane ps = new JScrollPane(m_monitor);
    getContentPane().add(ps, BorderLayout.CENTER);load();
    this.addWindowListener(new WindowAdapter() {
    public void windowClosing() {
    setVisible(true);
    System.exit(0);
    }
    });
    setVisible(true);
    }public void processWindowEvent(WindowEvent we) {
    if (we.getID() == WindowEvent.WINDOW_CLOSING) {
    save();
    }
    }public static void main(String[] args) {
    new TestFrame();
    }private void load() {
    try {
    InputStream in = new FileInputStream("c:\\temp\\test.rtf");
    m_doc = new DefaultStyledDocument(m_context);
    m_kit.read(in, m_doc, 0);
    System.out.println("Reading, Doc length = " + m_doc.getLength());
    m_monitor.setDocument(m_doc);
    in.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }private void save() {
    try {
    OutputStream out = new FileOutputStream("c:\\temp\\test.rtf");
    System.out.println("Saving, Doc length = " + m_doc.getLength());
    m_kit.write(out, m_doc, 0, m_doc.getLength());
    out.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    }
    提示

    将rtf出现的地方用html取代