Java从RTF获取纯文本

时间:2012-08-08 14:38:45

标签: java rtf

我的数据库中有一个包含RTF格式文本的列。 我怎样才能使用Java获得它的纯文本?

4 个答案:

答案 0 :(得分:1)

RTFEditorKit rtfParser = new RTFEditorKit();
Document document = rtfParser.createDefaultDocument();
rtfParser.read(new ByteArrayInputStream(rtfBytes), document, 0);
String text = document.getText(0, document.getLength());

这应该有效

答案 1 :(得分:0)

如果您可以尝试“AdvancedRTFEditorKit”,那可能会很酷。试试http://java-sl.com/advanced_rtf_editor_kit.html

我用它来创建一个完整的RTF编辑器,其中包含MS Word的所有支持。

答案 2 :(得分:0)

Apache POI还将阅读Microsoft Word格式,而不仅仅是RTF。

POI

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public String getRtfText(String fileName) {
   File rtfFile = null;
   WordExtractor rtfExtractor = null ;

   try {
    rtfFile = new File(fileName);

    //A FileInputStream obtains input bytes from a file.
    FileInputStream inStream = new FileInputStream(rtfFile.getAbsolutePath());

    //A HWPFDocument used to read document file from FileInputStream
    HWPFDocument doc=new HWPFDocument(inStream);

    rtfExtractor = new WordExtractor(doc);
   }
   catch(Exception ex)
   {
    System.out.println(ex.getMessage());
   }

    //This Array stores each line from the document file.
    String [] rtfArray = rtfExtractor.getParagraphText();

    String rtfString = "";

    for(int i=0; i < rtfArray.length; i++) rtfString += rtfArray[i];

    System.out.println(rtfString);
    return rtfString;
 }

答案 3 :(得分:0)

如果RTF文本位于JEditorPane

中,则此方法有效
String s = getPlainText(aJEditorPane.getDocument());

String getPlainText(Document doc) {
    try {
        return doc.getText(0, doc.getLength());
    }
    catch (BadLocationException ex) {
        System.err.println(ex);
        return null;
    }
}