JAVA解析RTF 文件

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

  首先通过Word 等文本编辑软件进行编辑 RTF 文档
  ![这里写图片描述](https://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);
    }
}

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

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值