从RTF中获取纯文本的Java方法

4

我在数据库中有一个列,其中保存了RTF格式的文本。

使用Java,我如何只获取其纯文本内容?


你可能会觉得这个很有趣。 - assylias
1
可能是重复的问题:从RTF字符串中提取文本的正则表达式 - John Smith
4个回答

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

这应该可以工作。


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;
 }


我需要类似于C#中的这样一个东西: static public string ConvertToText(string rtf) { RichTextBox rtb = new RichTextBox(); rtb.Rtf = rtf; return rtb.Text; } - Programmer
1
这个不行。POI不能解析RTF文档。(我试过了,得到了一个异常,说POI不能解析RTF文档!) - Mary
是的,我从Apache下载了最新的POI,但整个包中并没有hwpf。 - george_h
当然可以,它是Word的子组件(HWPF+XWPF)http://poi.apache.org/hwpf/index.html - Bernhard
3
以上代码不能打开RTF文件,会抛出"java.lang.IllegalArgumentException: The document is really a RTF file"异常。因此,我认为POI不支持打开RTF文件。 - Alex Lipov

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;
    }
}

0

我需要一个简单的解析器,可以获取像这样的字符串:{\rtf1\fbidis\ansi\ansicpg1255\deff0\deflang1037{\fonttbl{\f0\fnil\fcharset0 Tahoma;}} {\colortbl ;\red0\green0\blue0;} \viewkind4\uc1\pard\ltrpar\cf1\f0\fs18 2134\par } 并返回纯文本:'2134'。它不是来自文件,而是映射到字符串字段的简单VARCHAR2(4000)列。 - Programmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接