After searching for a few days to access the RTF file in Java, the results can only be described in two words-depressed !!!
I didn't want to write a summary, but I decided to write down some of the things I found over the past few days, hoping to enlighten my future applications.
The following is the only piece of code that I found available (using the self-contained RTF package in Java ):
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 cocould be big so add a scroll pane
Jscrollpane scroroller = 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 );
}
}
Next is my own test code:
Rtfeditorkit rtfeditor = new rtfeditorkit ();
// Jtp. setcontenttype ("text/RTF; charset = gb2312 ");
// Jtp. seteditorkit (rtfeditor );
Jep. setcontenttype ("text/RTF; charset = gb2312 ");
Jep. seteditorkit (rtfeditor );
Try {
Fileinputstream FCM = new fileinputstream ("D:/temp/myrtf. rtf ");
// Rtfeditor. Read (FCM, jtp. getdocument (), 0 );
Rtfeditor. Read (FCM, 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 ();
}
Finally, the results of the experiment are as follows:
I edited a piece of text in word, including an English, a Chinese, an image, and a mathematical formula.
The test result is: Except in English, all the other results are garbled !!!!!!!!!!!!!!!!