JAVA解析RTF 文件

来源:互联网 发布:灰鸽子软件下载 编辑:程序博客网 时间:2024/06/06 15:43

rtf文件
也称富文本格式(Rich Text Format, 一般简称为RTF),意为多文本格式是由微软公司开发的跨平台文档格式。大多数的文字处理软件都能读取和保存RTF文档。rtf是一种非常流行的文件结构,很多文字编辑器都支持它,vb等开发工具甚至还提供了richtxtbox的控件。
通过java进行读取操作时,需要注意的是项目和文件的编码格式问题,本次测试的项目环境编码为UTF-8, 而RTF 读取的字节数组的编码为 ISO-8859-1 ,输出字符串使用的编码格式为 GBK。

  首先通过Word 等文本编辑软件进行编辑 RTF 文档  ![这里写图片描述](http://img.blog.csdn.net/20160914174615971)

通过代码解析RTF 文件并打印结果

 /** * Project: optdata * Package: rtf * FileName: SelfTest.java */package rtf;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import javax.swing.text.BadLocationException;import javax.swing.text.DefaultStyledDocument;import javax.swing.text.rtf.RTFEditorKit;/** * @description 读取 RTF 文件内容 * @author LingeringNight   * */public class SelfTest {    /**     * @description  构造函数     */    public SelfTest() {    }    /**     * @description 从rtf文件中读取内容,使用java 内置函数对rtf 进行解析     * @param filePath     * @return     */    public static String getTextFromRtf(String filePath) {        String result = null;        File file = new File(filePath);        try {            DefaultStyledDocument styledDoc = new DefaultStyledDocument();            // 创建文件输入流            InputStream streamReader = new FileInputStream(file);            new RTFEditorKit().read(streamReader, styledDoc, 0);            //以 ISO-8859-1的编码形式获取字节byte[], 并以 GBK 的编码形式生成字符串            result = new String(styledDoc.getText(0, styledDoc.getLength()).getBytes("ISO8859-1"),"GBK");        } catch (IOException e) {            e.printStackTrace();        } catch (BadLocationException e) {            e.printStackTrace();        }        return result;    }    public static void main(String[] args) throws IOException {        String result = getTextFromRtf("D:\\temp\\china.rtf");        System.out.println(result);    }}

输出结果:
这里写图片描述

0 0
原创粉丝点击