利用JAVA读写rtf文档

今天尝试用JAVA来读写RTF文档,API中提供了类RTFEditorKit来对富文本的读写,类放在

javax.swing.text.rtf.RTFEditorKit,虽然放在swing下面,但却不是由swing团队编写的。
RTFEditorKit提供了两个主要方法来读写,分别是read和write;
例子中我用的是

read(InputStream in, Document doc, int pos)

write(OutputStream out, Document doc, int pos, int len)

import java.io.*;import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.*;public class AccessRTF {String text;DefaultStyledDocument dsd;RTFEditorKit rtf;/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubAccessRTF readRTF=new AccessRTF();readRTF.readRtf(new File("e:\\1.rtf"));readRTF.writeRtf(new File("e:\\out.rtf"));}public void readRtf(File in) {rtf=new RTFEditorKit();dsd=new DefaultStyledDocument();try {rtf.read(new FileInputStream(in), dsd, 0);text = new String(dsd.getText(0, dsd.getLength());System.out.println(text);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void writeRtf(File out) {try {rtf.write(new FileOutputStream(out), dsd, 0, dsd.getLength());} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部