从RTF文件中读取文本

Stu*_*ner 1 java apache-poi

我试图使用Apache POI读取rtf文件,但我发现它有问题.它报告无效标头例外.好像POI不支持rtf文件.有没有办法使用任何开源java API读取.rtf .(我听说过Aspose API,但它不是免费的)

有解决方案??

Lot*_*NSW 6

你可以试试RTFEditorKit.它也支持图像和文本.

或者看看这个答案:Java API将RTF文件转换为Word文档(97-2003格式)

没有免费的图书馆支持这一点.但是自己创建一个基本的比较函数可能并不难.您可以读入rtf文件,然后像这样提取文本:

// read rtf from file
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit rtfKit = p.getEditorKitForContentType("text/rtf");
rtfKit.read(new FileReader(fileName), p.getDocument(), 0);
rtfKit = null;

// convert to text
EditorKit txtKit = p.getEditorKitForContentType("text/plain");
Writer writer = new StringWriter();
txtKit.write(writer, p.getDocument(), 0, p.getDocument().getLength());
String documentText = writer.toString();
Run Code Online (Sandbox Code Playgroud)