Java中存取Rtf文件

狂找了几天在Java中存取Rtf文件的方法,结果只能用两个字形容——郁闷!!!
本来不想写总结的,不过想 到这几天的辛苦,还是决定把找到的一点小东东写下来,希望能对以后的应用有所启迪。

下面是我找到的唯一可用的一段代码(使用Java中自带的Rtf包):
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.rtf.*;

class RTFView
    extends   JFrame
{
  public RTFView()
  {
    setTitle( "RTF Text Application" );
    setSize( 400, 240 );
    setBackground( Color.gray );
    getContentPane().setLayout( new BorderLayout() );

    JPanel topPanel = new JPanel();
    topPanel.setLayout( new BorderLayout() );
    getContentPane().add( topPanel, BorderLayout.CENTER );

    // Create an RTF editor window
    RTFEditorKit rtf = new RTFEditorKit();
    JEditorPane editor = new JEditorPane();
    editor.setEditorKit( rtf );
    editor.setBackground( Color.white );

    // This text could be big so add a scroll pane
    JScrollPane scroller = new JScrollPane();
    scroller.getViewport().add( editor );
    topPanel.add( scroller, BorderLayout.CENTER );

    // Load an RTF file into the editor
    try {
      FileInputStream fi = new FileInputStream( "test.rtf" );
      rtf.read( fi, editor.getDocument(), 0 );
    }
    catch( FileNotFoundException e )
    {
      System.out.println( "File not found" );
    }
    catch( IOException e )
    {
      System.out.println( "I/O error" );
    }
    catch( BadLocationException e )
    {
    }
  }

  public static void main( String args[] )
  {
    // Create an instance of the test application
    RTFView mainFrame  = new RTFView();
    mainFrame.setVisible( true );
  }
}

接下来是我自己的测试代码:
  RTFEditorKit rtfeditor=new RTFEditorKit();
//  jtp.setContentType("text/rtf; charset=gb2312");
//  jtp.setEditorKit(rtfeditor);
  jep.setContentType("text/rtf; charset=gb2312");
  jep.setEditorKit(rtfeditor);
  
  try {
   FileInputStream fis = new FileInputStream("D:/temp/myrtf.rtf");
//   rtfeditor.read(fis, jtp.getDocument(), 0);
   rtfeditor.read(fis, jep.getDocument(), 0);
  } catch (FileNotFoundException e) {
   System.err.println(e.toString());
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println(e.toString());
   e.printStackTrace();
  } catch (BadLocationException e) {
   System.err.println(e.toString());
   e.printStackTrace();
  }

最后是实验的结果:
我用Word编辑了一段文字,包括一段英文、一段中文、一张图片、一个数学公式。
测试的结果是:除了英文外,其他都是乱码!!!!!!!!!!!!!!!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值