java rtf_Java中存取Rtf文件 | 学步园

本文介绍了如何在Java中读取和显示RTF文件,提供了一个使用RTFEditorKit的示例代码。尽管代码能够成功读取包含英文的RTF文件,但对于中文、图片和数学公式等内容,显示结果出现乱码问题。
摘要由CSDN通过智能技术生成

狂找了几天在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编辑了一段文字,包括一段英文、一段中文、一张图片、一个数学公式。

测试的结果是:除了英文外,其他都是乱码!!!!!!!!!!!!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值