如何解决JTextPane中序列化的中文问题?
rox 2002-04-30 03:33:03 各位大虾,我现在正好做一个图文混排的东东,主要原理是将图形和文字(及相关样式)输出为二进制流的文件或写入数据库,基本的功能都已实现。
但只要其中的JTextPane里含有中文,再将JTextPane的内容转换为document对象,转成二进制流就会发生问题,输出报错。相关读写操作代码如下:
void openfile_actionPerformed(ActionEvent e) {
Frame frame = getFrame();
if (frame == null) frame = new Frame();
if (fileDialog == null) {
fileDialog = new FileDialog(frame);
}
fileDialog.setMode(FileDialog.LOAD);
fileDialog.show();
String file = fileDialog.getFile();
if (file == null) {
return;
}
String directory = fileDialog.getDirectory();
File f = new File(directory, file);
if (f.exists()) {
try {
FileInputStream fin = new FileInputStream(f);
ObjectInputStream istrm = new ObjectInputStream(fin);
Document doc = (Document) istrm.readObject();
if(textPane.getDocument() != null)
textPane.setDocument(doc);
frame.setTitle(file);
validate();
} catch (IOException io) {
System.err.println("IOException: " + io.getMessage());
} catch (ClassNotFoundException cnf) {
System.err.println("Class not found: " + cnf.getMessage());
}
} else {
System.err.println("No such file: " + f);
}
}//openfile
void savefile_actionPerformed(ActionEvent e) {
Frame frame = getFrame();
if (frame == null) frame = new Frame();
if (fileDialog == null) {
System.out.println("ready");
fileDialog = new FileDialog(frame);
System.out.println("ok");
}
fileDialog.setMode(FileDialog.SAVE);
fileDialog.show();
String file = fileDialog.getFile();
if (file == null) {
return;
}
String directory = fileDialog.getDirectory();
File f = new File(directory, file);
try {
FileOutputStream fstrm = new FileOutputStream(f);
ObjectOutput ostrm = new ObjectOutputStream(fstrm);
ostrm.writeObject(textPane.getDocument());
ostrm.flush();
} catch (IOException io) {
System.err.println("IOException: " + io.getMessage());
}
}//savefile
可是,写入时报错如下:
IOException: java.lang.Object
读出式报错如下:
IOException: writing aborted; java.io.NotSerializableException: java.lang.Object
此程序在JDK1.3.0环境下,无需重新编译,直接运行,对中文的支持很好,一点问题没有。但JDK1.3.1_02和JDK1.4.0下运行均报错,但公司的工程已经统一使用JDK1.4.0,而且部分主要程序已经是用了新函数,所以要麻烦各位了!
请问,这是不是中文的问题,还是其他的什么原因呢?
如果是中文的问题,是不是要把整个UI或其他的相关的文字属性都设置成为Unicode。那具体该怎么设置呢?
希望各位高手指点小弟的迷津!
不胜感激!
(此程序是JDK的demo中Stylepad.jar源文件的一部分,希望对各位大虾分析问题有所帮助,谢谢!)