Java中的RTF到纯文本

如何在Java中将RTF字符串转换为纯文本? 显而易见的答案是使用Swing的RTFEditorKit,这似乎是互联网上的常见答案。 但是声称返回纯文本的write方法实际上并没有实现……它的硬编码只是在Java6中抛出IOException。

我在Java 6中使用Swing的RTFEditorKit,如下所示:

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

那就是工作。

试试Apache Tika: http : //tika.apache.org/0.9/formats.html#Rich_Text_Format

您可以将RTF Parser Kit视为Swing RTFEditorKit的轻量级替代品。 下面的行显示了从RTF文件中提取纯文本。 从输入流中读取RTF文件,将提取的文本写入输出流。

 new StreamTextConverter().convert(new RtfStreamSource(inputStream), outputStream, "UTF-8"); 

(完全披露:我是RTF Parser Kit的作者)

以下是以纯文本forms解析和编写RTF的完整代码

  import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.rtf.RTFEditorKit; public class rtfToJson { public static void main(String[] args)throws IOException, BadLocationException { // TODO Auto-generated method stub RTFEditorKit rtf = new RTFEditorKit(); Document doc = rtf.createDefaultDocument(); FileInputStream fis = new FileInputStream("C:\\SampleINCData.rtf"); InputStreamReader i =new InputStreamReader(fis,"UTF-8"); rtf.read(i,doc,0); // System.out.println(doc.getText(0,doc.getLength())); String doc1 = doc.getText(0,doc.getLength()); try{ FileWriter fw=new FileWriter("B:\\Sample INC Data.txt"); fw.write(doc1); fw.close(); }catch(Exception e) { System.out.println(e); } System.out.println("Success..."); } }