您的位置:首页 > 编程语言 > Java开发

Java中存取Rtf文件的程序

2008-04-09 21:18 471 查看
狂找了几天在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编辑了一段文字,包括一段英文、一段中文、一张图片、一个数学公式。
测试的结果是:除了英文外,其他都是乱码!!!!!!!!!!!!!!!!

该文章转载自网络大本营:http://www.xrss.cn/Dev/JAVA/2007111217579.Html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: