如何在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());
那就可以了。
new StreamTextConverter().convert(new RtfStreamSource(inputStream), outputStream, "UTF-8");
MyRtfListener
的引用来自RTF解析器工具包自述文件,该文件说明了您需要提供自己的监听器的情况。 - Jon Iles这里是将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...");
}
}