import java.awt.Color;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.rtf.RTFEditorKit;

public class tt2 {
    static JTextPane text;

    public static void main(String[] a) throws Exception {
        JFrame f = new JFrame();
        f.setBounds(200, 600, 400, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        text = new JTextPane();
        text.setEditorKit(new RTFEditorKit());

        MutableAttributeSet attrBackground = new SimpleAttributeSet();
        StyleConstants.setBackground(attrBackground, Color.YELLOW);
        MutableAttributeSet attrForeground = new SimpleAttributeSet();
        StyleConstants.setForeground(attrForeground, Color.GREEN);

        text.getDocument().insertString(0, "yellow_background\n", attrBackground);
        text.getDocument().insertString(0, "green_foreground ", attrForeground);
        write();
        read();

        f.getContentPane().add(text);
        f.setVisible(true);
    }

    static void write() {
        try (OutputStream o = Files.newOutputStream(Paths.get("test.rtf"))) {
            text.getEditorKit().write(o, text.getDocument(), 0, 0);
        } catch (Exception e2) {
            throw new RuntimeException(e2);
        }
    }

    static void read() {
        try (InputStream in = Files.newInputStream(Paths.get("test.rtf"))) {
            text.getEditorKit().read(in, text.getDocument(), 0);
        } catch (Exception e2) {
            throw new RuntimeException(e2);
        }
    }
}
