从文件中读取格式化数据

时间:2017-12-29 18:07:55

标签: java swing

import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.rtf.RTFEditorKit;

public class Main extends JFrame {
    public Main() throws Exception{
        setSize(400, 240);
        JTextPane topPanel = new JTextPane();
        StyledDocument doc;
        doc=topPanel.getStyledDocument();
        SimpleAttributeSet keyWord = new SimpleAttributeSet();
        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel, BorderLayout.CENTER);
        RTFEditorKit rtf = new RTFEditorKit();
        JEditorPane editor = new JEditorPane();
        editor.setEditorKit(rtf);
        topPanel.add(editor);
        FileInputStream fi=new FileInputStream("test.rtf");
        FileOutputStream fo=new FileOutputStream("test2.rtf");
        keyWord.getAttribute(fi);
        rtf.read(fi, editor.getDocument(), 0);
        try {
            doc.insertString(doc.getLength(), "Test\ntest2", keyWord);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        rtf.write(fo, doc, 0, 0);
        fo.close();
        fi.close();
    }

    public static void main(String args[]) throws Exception{
        Main mainFrame = new Main();
        mainFrame.setVisible(true);
    }
}

嗨! 我有一个关于格式化数据的问题。我想从文件" test.rtf"获得格式化日期。对象" keyWord",因为我想创建具有相同格式化数据的新字符串并将其保存到" test2.rtf"。怎么做?

1 个答案:

答案 0 :(得分:0)

在此示例中,List<String>正被复制到附加JTextPane的{​​{1}}。

SimpleAttributeSet