今天尝试用JAVA来读写RTF文档,API中提供了类RTFEditorKit来对富文本的读写,类放在
javax.swing.text.rtf.RTFEditorKit,虽然放在swing下面,但却不是由swing团队编写的。
RTFEditorKit提供了两个主要方法来读写,分别是read和write;
例子中我用的是
|
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 stub
AccessRTF 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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeRtf(File out) {
try {
rtf.write(new FileOutputStream(out), dsd, 0, dsd.getLength());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}